gpt4 book ai didi

javascript - 将数组添加到javascript中的对象数组

转载 作者:行者123 更新时间:2023-11-30 07:48:47 24 4
gpt4 key购买 nike

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

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

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

最佳答案

像这样?

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)

关于javascript - 将数组添加到javascript中的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59319572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com