Looking to iterate through object values and append text if the key matches in JavaScript. The object is as follows:
{
"id": "n27",
"name": "Thomas More",
"className": "level-1",
"children": [
{
"id": "n1",
"name": "Rousseau",
"className": "level-2",
"children": [
{
"id": "n2",
"name": "Machiavelli",
"className": "level-3",
"children": [
{
"id": "n9",
"name": "Edison, Thomas",
"className": "level-4"
}
]
}
]
},
{
"id": "n3",
"name": "Einstein",
"className": "level-2",
"children": [
{
"id": "n10",
"name": "Arf, Cahit",
"className": "level-3",
"children": [
{
"id": "n15",
"name": "Rawls, John",
"className": "level-4"
}
]
},
{
"id": "n12",
"name": "Smith, Adam",
"className": "level-3",
"children": [
{
"id": "n11",
"name": "Kant, Immanuel",
"className": "level-4"
}
]
}
]
},
{
"id": "n60",
"name": "Turing, Alan",
"className": "level-2"
}
]
}
The goal is to include " YES"
to their existing className
's. The updated object should appear like this:
{
"id": "n27",
"name": "Thomas More",
"className": "level-1 YES",
"children": [
{
"id": "n1",
"name": "Rousseau",
"className": "level-2 YES",
"children": [
{
"id": "n2",
"name": "Machiavelli",
"className": "level-3 YES",
"children": [
{
"id": "n9",
"name": "Edison, Thomas",
"className": "level-4 YES"
}
]
}
]
},
{
"id": "n3",
"name": "Einstein",
"className": "level-2 YES",
"children": [
{
"id": "n10",
"name": "Arf, Cahit",
"className": "level-3 YES",
"children": [
{
"id": "n15",
"name": "Rawls, John",
"className": "level-4 YES"
}
]
},
{
"id": "n12",
"name": "Smith, Adam",
"className": "level-3 YES",
"children": [
{
"id": "n11",
"name": "Kant, Immanuel",
"className": "level-4 YES"
}
]
}
]
},
{
"id": "n60",
"name": "Turing, Alan",
"className": "level-2 YES"
}
]
}
I attempted to achieve this but it applies to all keys:
const addToClassName = (datasource, fn) => {
return Object.fromEntries(Object
.entries(datasource, fn)
.map(([k, v]) => [k, v && v.children != undefined && v.children.length > 0 ? addToClassName(v.children, fn) : fn(v)])
);
}
let res = addToClassName(obj, v => v + ' YEP');
Any suggestions on how to accomplish this?