I have object with nested fields than named subItem I need to change names of this field to children.
How can this functionality be neatly implemented, perhaps there are ways besides recursion?
let data = [
{
name: 'Alex',
subItem: [
{
name: 'Den',
subItem: [
]
}
]
}
]
function transformData = (data) => {
return data.map(stat=>{
})
}
console.log(transformData(data))
//shoud be
let data = [
{
name: 'Alex',
children: [
{
name: 'Den',
children: []
}
]
}
]
Javascript already includes a recursive object transformer, JSON. stringify with replacer function:
let data = [
{
name: 'Alex',
subItem: [
{
name: 'Den',
subItem: [ {name: 'Foo', subItem: []} ],
}
]
}
]
JSON.stringify(data, function(_, v) {
if (v.subItem) {
v.children = v.subItem
delete v.subItem
}
return v
})
console.log(data)
In the simple case like this, you can also just manipulate the JSON string directly:
newData = JSON.parse(
JSON.stringify(data)
.replaceAll(`"subItem":`, `"children":`))