Elango
Elango

Reputation: 411

Object, key value map to JSON array

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

Upvotes: 0

Views: 4291

Answers (2)

Diamond
Diamond

Reputation: 3428

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);

Upvotes: 6

Nasir Uddin
Nasir Uddin

Reputation: 191

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

Upvotes: 1

Related Questions