0

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.

2
  • Not clear what you want to achieve, the resulting object doesn't contain all the properties in the intial array Commented Nov 26, 2020 at 17:09
  • The output should have a:true since it is present in the second object. Commented Nov 26, 2020 at 17:22

3 Answers 3

7

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)

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

Comments

1

I would use a Array.forEach() and Object.assign() like so:

const arr = [{id:1, a:true, b:[]},
 {id:2, a:false, b:[]},
 {id:3, foo:'', bar:{}},
 {id:4, bla:[1,2,3], blabla:{x: 1}}];

const obj = {};
arr.forEach(el => Object.assign(obj, el));


console.log(obj);

forEach() iterates through each element in your array and Object.assign applies the properties of el to the existing Object obj. At each iteration it will create properties that don't exist in obj or reassign the value of properties that do exist.

2 Comments

"I would use a Array.map" why would you use .map() when you don't have a mapping operation but just perform simple iteration?
Excellent point! I updated to use forEach(). I actually upvoted @adiga's response because I prefer it and I always forget about spread.
0
const data = [{id:1, a:true, b:[]},
              {id:2, a:false, b:[]},
              {id:3, foo:'', bar:{}},
              {id:4, bla:[1,2,3], blabla:{x: 1}}];
let result = {};
    data.map((item) => {
        result = {...result, ...item};
    }
)
console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.