1 回答

TA貢獻2016條經驗 獲得超9個贊
使用Object.keys(),您可以使用Array.map()迭代對象的每個鍵,以返回所需的 HTML 并使用語法顯示每個對象鍵的值myObj[key]
。
工作示例:https ://codesandbox.io/s/react-stackoverflow-60783297-ozjeu
請參閱下面代碼中的注釋以獲取解釋...
// Your object.
const myObj: FakeType = {
? value: {
? ? name: "Foo",
? ? id: 99
? },
? x: 5
};
// Function to get value of an object with key name and unquote value object props.
// Typing `obj: any` is necessary to avoid TypeScript to complain
// about the type of the key value you're trying to retrieve.
const getValue = (obj: any, key: string) => {
? const value = obj[key];
? const stringify = JSON.stringify(value);
? const unquoted = stringify.replace(/"([^"]+)":/g, "$1:");
? return unquoted;
};
// Loop through `myObj` keys and display its value
// using the `getValue()` function implemented above.
return (
? <React.Fragment>
? ? {Object.keys(myObj).map(key => (
? ? ? <div>
? ? ? ? {key}: {getValue(myObj, key)}
? ? ? </div>
? ? ))}
? </React.Fragment>
);
- 1 回答
- 0 關注
- 110 瀏覽
添加回答
舉報