[英]Turn array into objects, and add key values from another object
我有兩個相同長度的 arrays:
一個簡單的數組
arr1 = [1,2,3]
和另一個對象數組
arr2 = [
{cat: "a", other: 0},
{cat: "b". other: 0},
{cat: "c", other: 0}
]
我想將兩個 arrays 組合成一個新數組,從第一個數組中獲取值並為它們提供鍵node
,並將所有cat
組合如下:
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);
您可以通過它 map 構建數組並同時創建新對象
這個將所有對象合並在一起
arr1.map((value, idx) => ({ ...arr2[idx], node: value }))
如果你只想得到 arr2 的貓,那么就這樣做
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.