最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Object, key value map to JSON array - Stack Overflow

programmeradmin8浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 6

You 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'}]
发布评论

评论列表(0)

  1. 暂无评论