简体   繁体   English

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

[英]Turn array into objects, and add key values from another object

I have two arrays of the same length:我有两个相同长度的 arrays:

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:我想将两个 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);

You can just map through it and build the array and create the new objects at the same time您可以通过它 map 构建数组并同时创建新对象

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如果你只想得到 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