Find elements with specific value in a nested array with unknown depth - javascript

I have an array with objects for which the nesting depth is unknown and can be different. An example of such an array looks like that:
let exampleArray = [
{
id: 'some-id',
label: "Item 1",
children: [
{
id: 'some-id',
label: "Child 1",
children: [
{
id: 'some-id', // How to find this for example?
label: "Child 2",
children: []
}
]
}
]
},
{
id: 'some-id',
label: "Item 2",
children: [
{
id: 'some-id',
label: "Child 1",
children: [
{
id: 'some-id',
label: "Child 2",
children: []
}
]
}
]
}
]
Each array item can have a nested array children. The basic structure is the same as the parent one.
The challenge
When I for example want to delete a nested element with a specific id, how could I do this? I think it would not be the best practice to start iterations with a static number of loops, because I don't know how big the array is nested.
If I know the ID from the children element, can I say something like: "Iterate the entire array including all nesting and find the element with the ID xy?".
Or what would be the best practice to handle such nested arrays?

A recursive function is likely what you're looking for:
function deleteById(data, id){
for(var x = 0; x < data.length; x++){
if(data[x].id === id){
data.splice(x, 1); // if it matches, remove it from the array
}
else{
deleteById(data[x].children, id);
}
}
}

Related

Returning the ids from the object within the arrays

I have a multidimensional javascript array of objects that I am trying to use to simply collate the Unit id into a new array as shown below.
What is the best solution for returning the id within the inner value so I just get an array of the ids whatever I try seems to not work
[
{
units: [
{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [
{
id: 10000334,
name: "Group 4",
},
],
},
]
Expected output - just return an array with simply the ids
e.g
ids = [ 10000282, 10000340, 10000341, 10000334 ]
Assuming that data is in variable data:
> data.map(o => o.units.map(u => u.id)).flat()
[ 10000282, 10000340, 10000341, 10000334 ]
This assumes you're in an environment where .flat() is a thing.
If that's not the case, the longer way around is
const ids = [];
data.forEach(o => {
o.units.forEach(u => {
ids.push(u.id);
});
});

Deleting a child from a nested object structure in JavaScript [duplicate]

In my application I create a JavaScript object based on a JSON similar to this:
{
name: "root",
id: 112,
children: [
{
name: "child one",
id: 231,
children: [
{name: "grand child 1", id: 334, children: []},
{name: "grand child 2", id: 784, children: []}
]
},
{
name: "child two",
id: 343,
children: []
}
]
}
How can I remove any Child by his id? Please note that I don’t know the static path to the node e.g id == 334 so I am wondering how I could remove that node with just knowing it's id.
function del(obj,id){
obj.children = obj.children.filter(el => {
if(el.children) del(el,id);//delete subnodes
return el.id !== id; //delete this
});
}
A recursive approach to traverse the objects, usable as:
del(
{ children:[ { id:1 }, { id:2, children:[{id:1}] }] },
1
);
check this :
var abc = your json object;
//now filter the item based on id
abc = jQuery.grep(
abc.children,
function (item,index) {
return item.id != "343";
});
hope it helps.
var delIt = function (obj,id) {
return obj.children = obj.children.filter(function (child) {
if(child.children) delIt(child,id);
return child.id!=id;
});
}
var x= delIt(Tobj,335);
You can use filter function to collect items which are not equals to given id

Fastest possible object remapping for nested structure

Assume we have two different structures from two different APIs. Each has a different schema.
We have this as a return from API #1
[
{
Id: "test1",
Title: "label 1",
Children: [
{
Id: "test2",
Title: "label 2",
Children: [
{
Id: "test3",
Title: "label 3"
}
]
}
]
}
]
I need to convert it to the following scheme:
[
{
value: "test1",
label: "label 1",
children: [
{
value: "test2",
label: "label 2",
children: [
{
value: "test3",
label: "label 3"
}
]
}
]
}
]
So far I have come up with this method:
const transformItem = ({ Id, Title, Children }) => ({
value: Id,
label: Title,
children: Children ? transformData(Children) : null
});
const transformData = arr => arr.map(item => transformItem(item));
// Process data
const DataForApi2 = transformData(DataFromApi1);
From the limited benchmarking I performed and from what I can tell, in V8 (which is 95+% of our userbase) this looks fast enough as I'm not mutating any data structure (ergo hot objects are intact and retain performance) and using everything under a scope so I don't waste memory. Seems to be of linear complexity and not too bad if only performed once per client loading the app (only the first time after login).
In terms of runtime you're right this is probably the fastest we can get with O(n).
You could improve your space complexity by converting your solution from recursive to iterative. It saves space on the callstack which helps in extreme cases where trees go extremely deep.

Identify circular dependency in a Json object and remove all element after 2 depth

I have a json object something like this:
var temp1 = {
name: "AMC",
children: [
{
name: "cde",
children: [
{
name: "AMC",
children: [
{
name: "cde",
children: [
{
name: "AMC",
children: [
//.............. continues as curcular depndency
]
}
]
}
]
}
]
},
{
name: "mnp",
children: [
{
name: "xyz",
children: []
}
]
}
]
}
Due to this cicular dependency, JSON.stringify is failing.
I have done enough google and searching to get the solution for this but could not find much help.
So here basically I want to detect a circular dependency in the json object and add a new key to the object, saying cricular: true and remove all the subsequent node.
So here is the result output what I am looking :
var temp1 = {
name: "AMC",
children: [
{
name: "cde",
circular: true,
children: [ // No children here as it is curcular dependency
]
},
{
name: "mnp",
children: [
{
name: "xyz",
children: []
}
]
}
]
}
There is a way, which I think can solve it, where I can loop through all the children unless there is no children upto maximum 2 levels, but that way I will miss valid children which are having depth more than 3.
I hope my question is clear. If not please let me know I will try to expand this further.
A recursive function solves this:
function check(stack,parent, obj){
stack = stack || []; //stack contains a list of all previously occurred names
var found = stack.find(function(parent){
return (parent==obj.name && obj.children.length>0); //checks to see if the current object name matches any in the stack.
});
if(!found && obj.children.length>0){
stack.push(obj.name); //adds the current object name to the list.
obj.children.forEach(function(child){
check(stack,obj, child);//recursively checks for all children.
})
}
else if(found){
parent.children=[];
parent.circular=true;
stack.pop(obj.name);
return;
}
else{
return;
}
}
check([],temp1, temp1)
This leads to alteration of the original object passed.
Hope this helps!
use console.table(circularObj) to help you in debugging

How to remove an nested JSON object using id

In my application I create a JavaScript object based on a JSON similar to this:
{
name: "root",
id: 112,
children: [
{
name: "child one",
id: 231,
children: [
{name: "grand child 1", id: 334, children: []},
{name: "grand child 2", id: 784, children: []}
]
},
{
name: "child two",
id: 343,
children: []
}
]
}
How can I remove any Child by his id? Please note that I don’t know the static path to the node e.g id == 334 so I am wondering how I could remove that node with just knowing it's id.
function del(obj,id){
obj.children = obj.children.filter(el => {
if(el.children) del(el,id);//delete subnodes
return el.id !== id; //delete this
});
}
A recursive approach to traverse the objects, usable as:
del(
{ children:[ { id:1 }, { id:2, children:[{id:1}] }] },
1
);
check this :
var abc = your json object;
//now filter the item based on id
abc = jQuery.grep(
abc.children,
function (item,index) {
return item.id != "343";
});
hope it helps.
var delIt = function (obj,id) {
return obj.children = obj.children.filter(function (child) {
if(child.children) delIt(child,id);
return child.id!=id;
});
}
var x= delIt(Tobj,335);
You can use filter function to collect items which are not equals to given id

Categories

Resources