繁体   English   中英

将数组转为对象,并从另一个 object 添加键值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM