我有一个包含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函数中使用define数组并将其推入,那么我又得到了index
0和1。
如何在这里获得预期的结果。
答案 0 :(得分:2)
要获取具有所需键的单个对象,可以将所有项目分配给带有Object.assign
和spread syntax ...
的单个对象。
lib_struct.c
let input = [{ array1: [{ id: 1, name: "Test 1" }, { id: 2, name: "Test 2" }] }, { array2: [{ id: 1, name: "Test 1" }, { id: 2, name: "Test 2" }] }],
object = Object.assign(...input);
console.log(object)
您的代码不起作用,因为结果是最新的作业
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:2)
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; }
答案 2 :(得分:0)
使用代码
function convert(arr) {
let obj = new Object();
arr.forEach((value, key) => {
obj[key] = value;
});
return obj;
}
您正在forEach的每次迭代中进行obj = value;
,这意味着您每次都将obj重新分配为新值。
答案 3 :(得分:0)
您只需要在对象中使用foreach函数的关键参数即可。我在下面附上代码,您可以查看。
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[key] = value;
});
return obj;
}
console.log(convert(input))