I've a nested array, once the condition is met, it should give all the parent ids e.g. I've a data array, in which I should match the
var data = [{
"id": 96,
"name": "test1",
"items": [{
"id": 181,
"name": "Yes",
"items": []
}, {
"id": 182,
"name": "No",
"items": []
}]
}, {
"id": 109,
"name": "Test5",
"items": [{
"id": 219,
"name": "opt2",
"items": [{
"id": 76,
"name": "test3",
"items": [{
"id": 173,
"name": "Yes",
"items": []
}, {
"id": 174,
"name": "No",
"items": [{
"id": 100,
"name": "test2",
"items": [{
"id": 189,
"name": "Yes",
"items": []
}]
}]
}]
}]
}, {
"id": 224,
"name": "opt3",
"items": []
}]
}];
function getParentIds(data, id, parentIds) {
if (!parentIds) {
parentIds = [];
}
data.map(function(item) {
if (item.id === id) {
parentIds.push(item.id);
return parentIds;
} else if (item.items.length === 0) {
// do nothing
} else {
return getParentIds(item.items, id, parentIds);
}
});
}
console.log("Array list: " + getParentIds(data, 182, []));
Could you give me any suggestion on this?
This was a cool problem. It took me more than I expected to solve it, but here's a breadth-first search implementation:
var data = [{
"id": 96,
"name": "test1",
"items": [{
"id": 181,
"name": "Yes",
"items": []
}, {
"id": 182,
"name": "No",
"items": []
}]
}, {
"id": 109,
"name": "Test5",
"items": [{
"id": 219,
"name": "opt2",
"items": [{
"id": 76,
"name": "test3",
"items": [{
"id": 173,
"name": "Yes",
"items": []
}, {
"id": 174,
"name": "No",
"items": [{
"id": 100,
"name": "test2",
"items": [{
"id": 189,
"name": "Yes",
"items": []
}]
}]
}]
}]
}, {
"id": 224,
"name": "opt3",
"items": []
}]
}];
function parentsOf( arr, id, parents){
if (parents.length)
return parents;
// I use for(;;) instead of map() because I need the return to exit the loop
for (var i = 0; i < arr.length; i++){
if ( arr[i].id == id){
//push the current element at the front of the parents array
parents.unshift( arr[i].id );
return parents;
};
if ( arr[i].items ){
parents = parentsOf(arr[i].items, id, parents);
// if the parents array has any elements in it it means we found the child
if (parents.length){
parents.unshift(arr[i].id);
return parents;
}
}
}
return parents;
}
console.log("Array list for 182: " + parentsOf(data, 182, []));
console.log("Array list for 174: " + parentsOf(data, 174, []));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With