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 }]
4 Answers 4
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)
answered Dec 13, 2019 at 9:29
mplungjan
180k29 gold badges183 silver badges246 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Saurabh Agrawal
I like your second approach :)
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);
answered Dec 13, 2019 at 9:29
Saurabh Agrawal
7,7553 gold badges31 silver badges52 bronze badges
3 Comments
Saurabh Agrawal
@mplungjan well can do it in both ways, So I preferred create new array instead of modifying existing one.
Prashant Pimpale
(=>) arrow functions are not supported in IE <11!Saurabh Agrawal
There are some alternatives for the same, so coders will have to take care of it.
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 Objects.
answered Dec 13, 2019 at 9:37
Jason
2671 gold badge2 silver badges8 bronze badges
Comments
Try this
for(let i = 0; i < distance.length; i++)
{
list[i].distance = distance[i];
}
Prashant Pimpale
10.7k10 gold badges52 silver badges88 bronze badges
answered Dec 13, 2019 at 9:29
Shashank
8301 gold badge6 silver badges14 bronze badges
Comments
lang-js
map's callback