英文:
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 = [{
"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)
<!-- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论