在javascript中将数组添加到对象数组

时间:2019-12-13 09:27:19

标签: javascript node.js

我有两个变量,分别是对象的数组和数组,我想将第一个变量(距离)的值添加到第二个变量(列表)

以下方法工作正常,但我想知道是否还有其他方法可以得到一些结果。

let distance = [100,200,300]
let list = [ {"city" : "paris"} , {"city" : "london"} , { "city" : "barcelona" }]
for(let i = 0; i < distance.length;i++){
  let listDistance = list.map(el => {
      return Object.assign({}, el, {distance:distance[i++]})
      return el
  });

console.log(listDistance) 
}


// output [ {city : paris , distance : 100 } , {city : london  , distance : 200 } , { city : barcelona , distance : 300 }]

4 个答案:

答案 0 :(得分:3)

尝试一下:

  let array1 = [100, 200, 300]
  let array2 = [{ "city": "paris" }, { "city": "london" }, { "city": "barcelona" }]
  let res = array2.map((value, index) => {
    return { ...value, distance: array1[index] }
  })
  console.log(res);

答案 1 :(得分:3)

喜欢吗?

let distance = [100,200,300]
let list = [ {"city" : "paris"} , {"city" : "london"} , { "city" : "barcelona" }]

list.forEach((city,i) => city.distance = distance[i])

console.log(list)

旧版浏览器

let distance = [100,200,300]
let list = [ {"city" : "paris"} , {"city" : "london"} , { "city" : "barcelona" }]

list.forEach(function(city,i) { city.distance = distance[i] })

console.log(list)

如果您需要新的数组,可以使用map:

const distance = [100,200,300]
let list = [ {"city" : "paris"} , {"city" : "london"} , { "city" : "barcelona" }]

let distList = list.map((city,i) => ({ ...city, distance : distance[i]}) )

console.log(distList)

答案 2 :(得分:0)

尝试一下

for(let i = 0; i < distance.length; i++)
{
   list[i].distance = distance[i];
}

答案 3 :(得分:0)

const listWithDistances = list.map(
  (item, index) => ({ ...item, distance: distance[index] })
)

这与您返回新Array中的新Object的示例的结果相同。