I have two arrays of the same length:
A simple array
arr1 = [1,2,3]
And another array of objects
arr2 = [
{cat: "a", other: 0},
{cat: "b". other: 0},
{cat: "c", other: 0}
]
I want to combine the two arrays into a new array, taking the values from the first array and giving them the key node
, and combining all the cat
s as below:
end = [
{node: 1, cat: "a"},
{node: 2, cat: "a"},
{node: 3, cat: "a"},
]
arr2 = [ {cat: "a", other: 0}, {cat: "b", other: 0}, {cat: "c", other: 0} ]; arr1 = [1,2,3]; let res = []; for (let i=0; i<arr1.length; i++) { res.push({node: arr1[i], cat: arr2[i].cat}); } console.log(res);
You can just map through it and build the array and create the new objects at the same time
This one merged all objects together
arr1.map((value, idx) => ({ ...arr2[idx], node: value }))
If you want to just get the cat of arr2 then do this
arr1.map((value, idx) => ({ cat: arr2[idx].cat, node: value }))
arr1 = [1,2,3]; arr2 = [ {cat: "a", other: 0}, {cat: "b", other: 0}, {cat: "c", other: 0} ]; end = arr1.map((value, idx) => ({ cat: arr2[idx].cat, node: value })); console.log(end)
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.