我有一个包含 key
及其 array
元素的数组
当我将它从数组转换为对象时,我得到 index
0 和 1 但这里我需要的索引应该是 array1
和 array2
let input = [{
"array1": [{
"id": 1,
"name": "Test 1"
}, {
"id": 2,
"name": "Test 2"
}]
},
{
"array2": [{
"id": 1,
"name": "Test 1"
},
{
"id": 2,
"name": "Test 2"
}
]
}
];
function convert(arr) {
let obj = new Object();
arr.forEach((value, key) => {
obj = value;
});
return obj;
}
console.log(convert(input))
所以在调用这个函数之后我得到了以下输出
{
"array2": [
{
"id": 1,
"name": "Test 1"
},
{
"id": 2,
"name": "Test 2"
}
]
}
但是这里我需要的输出应该是这样的
{
"array1": [
{
"id": 1,
"name": "Test 1"
},
{
"id": 2,
"name": "Test 2"
}
],
"array2": [
{
"id": 1,
"name": "Test 1"
},
{
"id": 2,
"name": "Test 2"
}
]
}
如果我在 convert 函数中使用定义数组并将其推送,那么我将得到 index
0 和 1。
我怎样才能在这里得到预期的结果。
最佳答案
Spreading (...
) 是关键:
let input = [{
"array1": [{
"id": 1,
"name": "Test 1"
}, {
"id": 2,
"name": "Test 2"
}]
},
{
"array2": [{
"id": 1,
"name": "Test 1"
},
{
"id": 2,
"name": "Test 2"
}
]
}
];
function convert(arr) {
return arr.reduce((acc, curr) => ({ ...acc, ...curr }), {});
}
console.log(convert(input))
.as-console-wrapper { max-height: 100% !important; top: auto; }
您也可以将它与 Object.assign
结合使用在数组本身上:
let input = [{
"array1": [{
"id": 1,
"name": "Test 1"
}, {
"id": 2,
"name": "Test 2"
}]
},
{
"array2": [{
"id": 1,
"name": "Test 1"
},
{
"id": 2,
"name": "Test 2"
}
]
}
];
function convert(arr) {
return Object.assign(...arr);
}
console.log(convert(input))
.as-console-wrapper { max-height: 100% !important; top: auto; }
关于javascript - 如何创建具有多个键和元素的单个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55530475/