Reputation: 13
i don't know the way so i need help please. So i have this object
{
"label": "root",
"children": [
{
"label": "a",
"value": "abc"
},
{
"label": "b",
"value": 123
},
{
"label": "c",
"children": [
{
"label": 0,
"children": [
{
"label": "d",
"value": "def"
},
{
"label": "e",
"value": 1
},
{
"label": "f",
"children": [
{
"label": 0,
"children": [
{
"label": "g",
"value": "ghi"
},
{
"label": "h",
"value": 456
}
]
}
]
}
]
},
{
"label": 1,
"children": [
{
"label": "i",
"value": 1
},
{
"label": "j",
"value": "abc"
},
{
"label": "asd",
"children": [
{
"label": 0,
"children": [
{
"label": "qwe",
"value": "kuracpalac"
},
{
"label": "rtz",
"value": "asdasdasdasd"
}
]
}
]
}
]
}
]
}
]
}
, and i need it to convert it to new object that looks like this one :
const obj = {
a: "abc",
b: 123,
c: [
{
d: "def",
e: 1,
f: [
{
g: "ghi",
h: 456
}
]
},
{
i: 1,
j: "abc",
asd: {
qwe: "kuracpalac",
rtz: "asdasdasdasd"
}
}
]
};
Thank you for you help :)!
Upvotes: 1
Views: 299
Reputation: 386881
You could use two functions, one for getting either an array, depending on the keys, if integer values or an assigned object. The other function returns an object with a new key/value pair, either a value or a nested object structure of the children array.
function assign(array) {
return Object.assign(0 in array[0] ? [] : {}, ...array);
}
function getObject({ label, value, children }) {
return { [label]: value || assign(children.map(getObject)) };
}
var data = { label: "root", children: [{ label: "a", value: "abc" }, { label: "b", value: 123 }, { label: "c", children: [{ label: 0, children: [{ label: "d", value: "def" }, { label: "e", value: 1 }, { label: "f", children: [{ label: 0, children: [{ label: "g", value: "ghi" }, { label: "h", value: 456 }] }] }] }, { label: 1, children: [{ label: "i", value: 1 }, { label: "j", value: "abc" }, { label: "asd", children: [{ label: 0, children: [{ label: "qwe", value: "kuracpalac" }, { label: "rtz", value: "asdasdasdasd" }] }] }] }] }] },
result = getObject(data).root;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2