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'}]