1 回答

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
使用Object.keys(),您可以使用Array.map()迭代對(duì)象的每個(gè)鍵,以返回所需的 HTML 并使用語(yǔ)法顯示每個(gè)對(duì)象鍵的值myObj[key]
。
工作示例:https ://codesandbox.io/s/react-stackoverflow-60783297-ozjeu
請(qǐng)參閱下面代碼中的注釋以獲取解釋...
// 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 關(guān)注
- 123 瀏覽
添加回答
舉報(bào)