I’ve an array of objects:
const arr = [
{
"topicId": 1,
"topicName": "Topic 1",
"topicIcon": {
"name": "Caret",
"class": "lmnicon lmnicon-caret-right"
},
"topicContent": "T1 topic content",
"children": [
{
"topicId": 4,
"topicName": "Topic 4",
"topicIcon": {
"name": "Caret",
"class": "lmnicon lmnicon-caret-right"
},
"topicContent": "T4 topic content"
},
{
"topicId": 5,
"topicName": "Topic 5",
"topicIcon": {
"name": "Caret",
"class": "lmnicon lmnicon-caret-right"
},
"children": [
{
"topicId": 6,
"topicName": "Topic 6",
"topicIcon": {
"name": "Caret",
"class": "lmnicon lmnicon-caret-right"
}
},
{
"topicId": 7,
"topicName": "Topic 7",
"topicIcon": {
"name": "Caret",
"class": "lmnicon lmnicon-caret-right"
}
},
{
"topicId": 8,
"topicName": "Topic 8",
"topicIcon": {
"name": "Caret",
"class": "lmnicon lmnicon-caret-right"
}
},
]
}
]
},
{
"topicId": 2,
"topicName": "Topic 2",
"topicIcon": {
"name": "Caret",
"class": "lmnicon lmnicon-caret-right"
},
"topicContent": "T2 topic content",
"children": [
{
"topicId": 9,
"topicName": "Topic 9",
"topicIcon": {
"name": "Caret",
"class": "lmnicon lmnicon-caret-right"
}
},
{
"topicId": 10,
"topicName": "Topic 10",
"topicIcon": {
"name": "Caret",
"class": "lmnicon lmnicon-caret-right"
}
}
]
}
]
const mapHeirarchy = list => list.flatMap(({ topicId, topicName, topicIcon, children = [] }) => {
const obj = {
'topicId': topicId,
'topicName': topicName,
'topicIcon': topicIcon,
'droppable': true, //add this
'draggable': true //add this
}
return [obj, ...mapHeirarchy(children)]
});
console.log(mapHeirarchy(arr))
I need to add this two properties droppable
and draggable
as true in objects as well as in nested childrens which might be ‘n’ levels deep.
Though I added the properties but I need to go back to the original ‘arr’ structure.
I’m not sure how can we go back or is there more correct way to achieve this.
2
Answers
Simply
map
instead of getting a flat array.You have to redesign your flattener so that it returns objects themselves rather than copies:
and then you can apply
map
to it:As a side node, argument object destructuring like this
only makes sense when you need a couple of properties from some potentially large object. If you need all props anyways, it makes no sense to "destructure" them, it is tedious and error-prone.