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 关注
- 79 浏览
添加回答
举报