我有如下格式的对象数组。它基本上是一个嵌套的对象数组。我试图使用递归函数来完成它,但是我未能组织嵌套的对象。
[
{
"id": "31a3sd2f1a3ds21f",
"name": "Energy device",
"child": [
{
"id": "65sa4d65a4sdf654adsf",
"name": "Device 2",
"child": [
{
"id": "65a4d65ad4s54adsf",
"name": "Device 3",
"child": []
}
]
}
]
},
{
"id": "6as54d54as5f",
"name": "Energy device 2",
"child": [
{
"id": "9a8s7df98a78sdf",
"name": "Device 4",
"child": [
{
"id": "65a4d65ad4s54adsf",
"name": "Device 5",
"child": []
}
]
},
{
"id": "65asd54as5f4",
"name": "Device 5-1",
"child": []
}
]
}
]我想把它转换成以下格式。
{
"31a3sd2f1a3ds21f": {
"65sa4d65a4sdf654adsf": {
"65a4d65ad4s54adsf": ""
}
},
"6as54d54as5f": {
"9a8s7df98a78sdf": {
"65a4d65ad4s54adsf": ""
},
"65asd54as5f4": ""
}
}有人能帮我吗?
发布于 2022-04-09 09:13:55
您可以将数组中的每个对象映射到形状[key, value]的新数组。对于每个对象,可以在回调参数({id, child}) => ...)中使用去剪切赋值提取id和子属性。然后,可以为该对象返回一个数组,该数组表示您构建的新对象的条目。键是当前对象的id,该值要么是一个基于child数组的新对象,可以通过递归调用来构建,要么是一个空字符串,如果您的当前对象没有任何子对象。这允许您在构建对象时将嵌套添加到对象中。最后,可以将arr的映射版本封装为对Object.fromEntries()的调用,该调用允许将[key, value]对条目的数组转换为对象:
const arr = [ { "id": "31a3sd2f1a3ds21f", "name": "Energy device", "child": [ { "id": "65sa4d65a4sdf654adsf", "name": "Device 2", "child": [ { "id": "65a4d65ad4s54adsf", "name": "Device 3", "child": [] } ] } ] }, { "id": "6as54d54as5f", "name": "Energy device 2", "child": [ { "id": "9a8s7df98a78sdf", "name": "Device 4", "child": [ { "id": "65a4d65ad4s54adsf", "name": "Device 5", "child": [] } ] }, { "id": "65asd54as5f4", "name": "Device 5-1", "child": [] } ] } ];
const mapToId = (arr) => Object.fromEntries(arr.map(({id, child}) => [
id, child.length ? mapToId(child) : ""
]));
const res = mapToId(arr);
console.log(res);
发布于 2022-04-09 09:41:01
我不知道为什么您希望最后一个子对象是空字符串而不是空对象,但如下所示:
function arrayToObject(array) {
// Create empty object if array has cildren, else create an empty string
const obj = array.length > 0 ? {} : '';
// Recursively add children to object
array.forEach((item) => {
obj[item.id] = arrayToObject(item.child);
});
return obj;
}https://stackoverflow.com/questions/71806514
复制相似问题