简体   繁体   中英

Add an array to array of objects in javascript

I have two variables which is an array and array of object, I want to add the value of first variable(distance) to second variable(list)

The following works fine, but I want to know if there's any other method to get some result.

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

Try this:

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

Like this?

 let distance = [100,200,300] let list = [ {"city" : "paris"} , {"city" : "london"} , { "city" : "barcelona" }] list.forEach((city,i) => city.distance = distance[i]) console.log(list)

Older browsers

 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)

If you need a new Array you can use 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)

Try this

for(let i = 0; i < distance.length; i++)
{
   list[i].distance = distance[i];
}
const listWithDistances = list.map(
  (item, index) => ({ ...item, distance: distance[index] })
)

This has the same result of your example of returning a new Array of new Object s.

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