0

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.

1
  • 1
    In your expected output, where is the input for { color: "Black", material: "iron", year_released: 1996, price: 5000, year_built: 1990 } coming from? And for that matter, spoiler is a spoiler in the first array and a material in the output? I think you'll clear up your data first. Commented Feb 26, 2021 at 10:17

2 Answers 2

3

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

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

Comments

0

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

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.