如何从两个不同的数组创建对象数组?

huangapple go评论57阅读模式
英文:

how to create array of objects from 2 different array?

问题

我有两个长度不同且每个数组中的项目数量是动态的数组。我想要合并这两个数组,并将finalArray作为输出。我该如何做?

const array1 = [7665, 7666];
const array2 = [
    {
        "id": 1,
        "name": "user-1",
    },
    {
        "id": 2,
        "name": "user-2",
    },
    {
        "id": 3,
        "name": "user-3",
    },
];

const finalArray = array2.map(item => {
    const obj = {};
    array1.forEach(num => {
        obj[num] = [];
    });
    obj["users"] = item["name"];
    return obj;
});

这段代码将会生成你所期望的finalArray

英文:

I have 2 arrays with different lengths and the number of items in each array is dynamic. I want to merge these 2 arrays and have the finalArray as an output. How can I do that?
I want to add each item in array1 to all objects of array2 as key and an empty array as value.

 const array1 = [7665,7666]
 const array2 = [
{
    "id": 1,
    "name": "user-1",
},
{
    "id": 2,
    "name": "user-2", 
},
{
    "id": 3,
    "name": "user-3",
},
  ]

 const finalArray = [
    {
      7665: [],
      7666: [],
      users: 'user-1',
    },
    {
      7665: [],
      7666: [],
      users: 'user-2',
    },
    {
      7665: [],
      7666: [],
      users: 'user-3',
    }
  ]

答案1

得分: 0

以下是翻译好的内容:

const array1 = [7665, 7666];
const array2 = [{
    "id": 1,
    "name": "user-1",
  },
  {
    "id": 2,
    "name": "user-2",
  },
  {
    "id": 3,
    "name": "user-3",
  },
];

const result = array2.map(({ id, name }) => ({
  ...array1.reduce((acc, cur) => ({
    ...acc,
    [cur]: []
  }), {}),
  users: name
}))

console.log(result)
英文:

Here you go:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const array1 = [7665, 7666];
const array2 = [{
    &quot;id&quot;: 1,
    &quot;name&quot;: &quot;user-1&quot;,
  },
  {
    &quot;id&quot;: 2,
    &quot;name&quot;: &quot;user-2&quot;,
  },
  {
    &quot;id&quot;: 3,
    &quot;name&quot;: &quot;user-3&quot;,
  },
];

const result = array2.map(({ id, name }) =&gt; ({ 
  ...array1.reduce((acc, cur) =&gt; ({ 
    ...acc, 
    [cur]: [] 
  }), {}), 
  users: name 
}))

console.log(result)

<!-- end snippet -->

The map creates one object per user from array2. The reduce converts each number in array1 to a key on the final user object.

huangapple
  • 本文由 发表于 2023年7月4日 20:57:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76612900.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定