简体   繁体   中英

Merge Two Array of Object based on its Index (Without Key) Javascript

I have a problem that make me stuck for a while. I am using Javascript . I have two arrays of object that look like this:

1st Array:

[ { color: "Red", material: "carbon" }, { color: "Black", material: "iron" } ]

2nd Array

[ [ { year_released: 2000 }, { price: 3000 }, { year_built: 1998 } ], [ { year_released: 1996 }, { price: 5000 }, { year_built: 1990 } ] ]

I need to merge those arrays of object to become like this:

[ { color: "Red", material: "carbon", year_released: 2000, price: 3000, year_built: 1998 }, { color: "Black", material: "iron", year_released: 1996, price: 5000, year_built: 1990 } ]

Please help me to solve this problem. Thank you so much.

You need to use Object.assign() to merge the objects and iterate through the target and source object arrays as per your requirements.

 const targets = [ { color: "Red", spoiler: "carbon" }, { color: "Blue", spoiler: "oxygen" } ]; const sources = [ [ { year_released: 2000 }, { price: 3000 }, { year_built: 1998 } ], [ { year_released: 1996 }, { price: 5000 }, { year_built: 1990 } ] ]; const returnedTargets = targets.map((target, i) => Object.assign({}, target, ...sources[i]) ); console.log(returnedTargets); // console.log(target, sources, returnedTargets); // [{"color":"Red","spoiler":"carbon"},{"color":"Blue","spoiler":"oxygen"}] // [[{"year_released":2000},{"price":3000},{"year_built":1998}],[{"year_released":1996},{"price":5000},{"year_built":1990}]] // [{"color":"Red","spoiler":"carbon","year_released":2000,"price":3000,"year_built":1998},{"color":"Blue","spoiler":"oxygen","year_released":1996,"price":5000,"year_built":1990}]

You can use spread operators:

 const arr1 = [{ color: "Red", spoiler: "carbon" }]; const arr2 = [[ { year_released: 2000 }, { price: 3000 }, { year_built: 1998 } ]]; console.log({...Object.assign({}, ...arr1), ...Object.assign({}, ...arr2[0]) });

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