Skip to content
Advertisement

Get all properties found in Object

I have an array of objects

const data = [{id:1, a:false, b:[5,4]},
 {id:2, a:true, b:[]},
 {id:3, c:'', d:{}},
 {id:4, e:[1,2,3], f:{h: 1}}];

basically I am trying to return an object that has all the properties found in the object, and then give me the latest value.

so it should give me the following result:

// { id: 4, a: false, b: [], c: '', d: {}, e: [1,2,3], f: {h: 1}}

I played around with Object.getOwnPropertyNames and Object.values, but been stuck for some time now , fairly new to JS.

Advertisement

Answer

You could use a simple call to Object.assign to merge all the objects inside data to a single object.

Object.assign({}, ...data)

The method can take any number of source objects to be merged. So, spread the array to pass them as parameters. Since the objects are merged in order, the later objects are preferred. If a property exists in multiple objects, the object with the higher index overwrites the previous value. So, id:4 appears in the output

Here’s a snippet:

const data = [{id:1, a:false, b:[5,4]},
 {id:2, a:true, b:[]},
 {id:3, c:'', d:{}},
 {id:4, e:[1,2,3], f:{h: 1}}];
 
const output = Object.assign({}, ...data)
console.log(output)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement