简体   繁体   中英

JavaScript Updating arrays with data from separate array

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.

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

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

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