I have an array of objects in the following format. It basically a nested array of objects. I tried to do it using a recursive function, but I failed to organize the nested object.
[
{
"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": []
}
]
}
]
I want to convert it to the following format.
{
"31a3sd2f1a3ds21f": {
"65sa4d65a4sdf654adsf": {
"65a4d65ad4s54adsf": ""
}
},
"6as54d54as5f": {
"9a8s7df98a78sdf": {
"65a4d65ad4s54adsf": ""
},
"65asd54as5f4": ""
}
}
Is there anyone who can help me?
CodePudding user response:
You can map each object within your array to new arrays of the shape [key, value]
. For each object, you can extract the id and child properties using desturcutring assignment in your callback argument ({id, child}) => ...)
. You can then return an array for that object that represents an entry for the new object your building. The key is the id
of the current object, and the value is either a new object based on the child
array which you can build by doing a recursive call, or an empty string if your current object doesn't have any children. This allows you to add the nesting to the objects as you build them. Finally, you can wrap the mapped version of your arr
into a call to Object.fromEntries()
which allows you to convert the array of [key, value]
pair entries into an object:
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);
CodePudding user response:
I don't know why you wanted the final child to be an empty string instead of an empty object, but here it is:
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;
}