I would like to convert an array of objects to a nested object using a recursive function.
The objective is to create a function that works whatever the depth of my inital array. You can see below the initial data with desired result + code snippet with attempt at solving this issue.
Initial array of objects
configurator: [
{
key: '-LLnLuLt6cn-vBpMWv-u',
name: 'CONFIGURATOR_1',
collections: [
{
key: '-LLnMWy69vACjys0QIGH',
name: 'COLLECTION_1',
options: [
{
key: '-LLnOxg5hsDYR-PcfjBT',
name: 'OPTION_1',
},
{
key: '-LLnP-O6TyHxIpPk9bCU',
name: 'OPTION_2',
},
],
},
{
key: '-LLnMYNyJmhSCPB-8lL1',
name: 'COLLECTION_2',
},
],
},
{ key: '-LLnLtLs7PjXSAW0PWCQ',
name: 'CONFIGURATOR_2',
}]
Desired outcome : Nested objects
configurator: {
'-LLnLuLt6cn-vBpMWv-u': {
name: 'CONFIGURATOR_1',
index: 0,
collections: {
'-LLnMWy69vACjys0QIGH': {
name: 'COLLECTION_1',
index: 0,
options: {
'-LLnOxg5hsDYR-PcfjBT': {
name: 'OPTION_1',
index: 0,
},
'-LLnP-O6TyHxIpPk9bCU': {
name: 'OPTION_2',
index: 1,
},
},
},
'-LLnMYNyJmhSCPB-8lL1': {
name: 'COLLECTION_2',
index: 1,
},
},
},
'-LLnLtLs7PjXSAW0PWCQ': {
name: 'CONFIGURATOR_2',
index: 1,
},
}
My attempt
Here is a code snippet of what I have tried so far. It only works with the first depth of the array. I believe this is the challenge to solve: how to dynamcilly add/'push' an object to a nested object ?
Hope someone can help. Cheers, Julien.
const data = {
configurator: [{
key: '-LLnLuLt6cn-vBpMWv-u',
name: 'CONFIGURATOR_1',
collections: [{
key: '-LLnMWy69vACjys0QIGH',
name: 'COLLECTION_1',
options: [{
key: '-LLnOxg5hsDYR-PcfjBT',
name: 'OPTION_1',
},
{
key: '-LLnP-O6TyHxIpPk9bCU',
name: 'OPTION_2',
},
],
},
{
key: '-LLnMYNyJmhSCPB-8lL1',
name: 'COLLECTION_2',
},
],
},
{
key: '-LLnLtLs7PjXSAW0PWCQ',
name: 'CONFIGURATOR_2',
}
]
};
const format = (object) => {
const result = {};
Object.keys(object).forEach((property) => {
if (Array.isArray(object[property])) {
object[property].forEach((test, index) => {
const {
key,
...content
} = test;
result[key] = {
index,
...content
};
format(content);
});
}
});
return result;
};
const formated = format(data);
console.log('@FORMATED__', formated);
Edited
function format(data) {
var result = {};
data.forEach(function(config, i) {
var obj = {
index: i
}
Object.keys(config)
.forEach(function(key) {
if (!Array.isArray(config[key])) {
if (key != "key") obj[key] = config[key];
} else {
obj[key] = format(config[key]);
}
});
result[config.key] = obj;
});
return result;
}
console.log(format(data));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments