I have two arrays both consisting of 30 items. Array 1: [ {cat, red} , {dog, blue} , ... ] Array 2: [ {1}, {2}, ... ]
My goal is to have Array 3 like so: [ {Cat, red, 1} , {dog, blue, 2} ... ] I am using JavaScript and cheerio to grab the data.
CodePudding user response:
Your objects look strange, {1}
isn't a valid object. Maybe you meant something like {id: 1}
?
Anyway, looks like you need something like this:
const arr3 = arr1.map((el, index) => {
return {
...el,
...arr2[index],
}
})
CodePudding user response:
It's hard to tell what the data actually looks like, since [ {cat, red} , {dog, blue} , ... ]
isn't valid JSON or anything, but the general idea would be to get the corresponding element from the other array by index, either using .map((el, index) => { // ... })
or just looping over it, so something like:
const arr1 = [{title: 'movieA', rank: '1' }, {title: 'MovieB', rank: '2'}]
const arr2 = [{score: 10}, {score: 20}]
console.log(arr1.map((el, i) => {
return { ...el, ...arr2[i] }
}));