javascript 如何映射对象的键,使 JSON 更容易在 React 中处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33037116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to map an object's keys to make JSON easier to handle in React
提问by CherryFlavourPez
If I have this JSON:
如果我有这个 JSON:
{
'name': 'Active user',
'config': {
'status': 'active',
}
},
{
'name': 'Paused user',
'config': {
'status': 'active',
}
}
Then I can render a React component and access the data easily:
然后我可以渲染一个 React 组件并轻松访问数据:
render: function() {
var panels = [];
this.props.accounts.forEach(function(account) {
panels.push(
<Tabs.Panel title={account.name}>
<h2>{account.name}</h2>
</Tabs.Panel>
);
});
return (<Tabs>{panels}</Tabs>);
}
...
React.render(<Tabs accounts={ACCOUNTS} />, document.body);
If my JSON is structured as below instead, how should I re-factor the render
function to work as I want?
如果我的 JSON 结构如下,我应该如何重构该render
函数以按我的意愿工作?
{
'Active User': {
'config': {
'status': 'active',
}
},
'Paused User': {
'config': {
'status': 'paused',
}
}
}
i.e. I no longer have a name
attribute to display.
即我不再有name
要显示的属性。
回答by Samuli Hakoniemi
Is this what you want?
这是你想要的吗?
var users = {
'Active User': {
'config': {
'status': 'active',
}
},
'Paused User': {
'config': {
'status': 'paused',
}
}
};
var usersWithName = Object.keys(users).map(function(key) {
var user = users[key];
user.name = key;
return user;
});
Where usersWithName
= [{"config":{"status":"active"},"name":"Active User"},{"config":{"status":"paused"},"name":"Paused User"}]
其中usersWithName
=[{"config":{"status":"active"},"name":"Active User"},{"config":{"status":"paused"},"name":"Paused User"}]