简体   繁体   中英

Use spread operator to combine an unknown number of objects

Here's what I'm trying to do.

Suppose I've got an array of objects like so:
const arr = [ {a:1, b:2}, {c:3, d:4}, {e:5, f:6} ];

I'm trying to convert this into one object, that looks like this:
const obj = {a:1, b:2, c:3, d:4, e:5, f:6};

I know that I can accomplish this with the spread operator like this:
const obj = {...arr[0], ...arr[1], ...arr[2]};

But what if I don't know how many objects are in arr ? It seems like there must be a way to loop through each object in the array and "spread" them into one object, but I can't seem to figure it out.

A reduce would work nicely here:

 const arr = [ {a:1, b:2}, {c:3, d:4}, {e:5, f:6} ]; const obj = arr.reduce((combo, item) => { return {...combo, ...item}; }, {}); console.log(obj) 

Spread it into assign like this:

 const arr = [ {a:1, b:2}, {c:3, d:4}, {e:5, f:6} ]; const obj = Object.assign({}, ...arr); console.log(obj); // {a:1, b:2, c:3, d:4, e:5, f:6} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM