admin管理员组文章数量:1391758
I receive data like this
{ '1': 'House',
'2': 'Town Home',
'3': 'Apartment' }
But I need Array of objects like this
[{id:"1", name:"House"},{id:"2", name:"Town Home"}]
I receive data like this
{ '1': 'House',
'2': 'Town Home',
'3': 'Apartment' }
But I need Array of objects like this
[{id:"1", name:"House"},{id:"2", name:"Town Home"}]
Share
Improve this question
edited Nov 20, 2019 at 9:28
Diamond
3,4484 gold badges21 silver badges41 bronze badges
asked Nov 20, 2019 at 8:45
ElangoElango
4114 silver badges25 bronze badges
3
- 1 Is the result Array of objects? – Diamond Commented Nov 20, 2019 at 8:52
- you have to parse the data at your end and make it just like this.... – abhikumar22 Commented Nov 20, 2019 at 8:55
- that is not a valid json you are trying to create – Sylens Commented Nov 20, 2019 at 8:57
2 Answers
Reset to default 6You can use Object.entries()
to convert the object into Array of objects.
const src = {
'1': 'House',
'2': 'Town Home',
'3': 'Apartment'
};
const dist = Object.entries(src).map(([id, name]) => ({ id, name }));
console.log(dist);
Every jSon object must be like key value pairs, like your first object
{ '1': 'House',
'2': 'Town Home',
'3': 'Apartment' }
but your second object is not a valid json object. But you can make an Array from your first object to second one
[{id:"1", name:"House"},{id:"2", name:"Town Home"}]
if you wish to make something like this, you can follow those steps:
// store your object to a variable
const a = { '1': 'House', '2': 'Town Home', '3': 'Apartment' }
// create array from variable 'a'
const b = Object.keys(a).map(k => ({id: k, name: a[k]}))
this will make variable b
like this
[{id: '1', name: 'House'}, {id: '2', name: 'Town Home'}, {id: '3', name: 'Apartment'}]
本文标签: javascriptobjectkey value map to JSON arrayStack Overflow
版权声明:本文标题:javascript - Object, key value map to JSON array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744772674a2624435.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论