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"}]
3
  • 1
    Is the result Array of objects? Commented Nov 20, 2019 at 8:52
  • you have to parse the data at your end and make it just like this.... Commented Nov 20, 2019 at 8:55
  • that is not a valid json you are trying to create Commented Nov 20, 2019 at 8:57

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.