Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  193] [ 6]  / answers: 1 / hits: 152349  / 11 Years ago, sat, march 16, 2013, 12:00:00

I have a json array which looks something like this:



  {
id: 1,
children: [
{
id: 2,
children: {
id: 3,
children: {
id: 4,
children:
}
}
},
{
id: 2,
children: {
id: 3,
children: {
id: 4,
children:
}
}
},
{
id: 2,
children: {
id: 3,
children: {
id: 4,
children:
}
}
},
{
id: 2,
children: {
id: 3,
children: {
id: 4,
children:
}
}
},
{
id: 2,
children: {
id: 3,
children: {
id: 4,
children:
}
}
},
{
id: 2,
children: {
id: 3,
children: {
id: 4,
children:
}
}
},
{
id: 2,
children: {
id: 3,
children: {
id: 4,
children:
}
}
}]
}


I would like to have a function which removes the elements which has the children empty. How can I do it? I am not asking for the answer, only suggestions


More From » jquery

 Answers
13

To iterate through the keys of an object, use a for .. in loop:



for (var key in json_obj) {
if (json_obj.hasOwnProperty(key)) {
// do something with `key'
}
}


To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.



Removing a property of an object can be done by using the delete keyword:



var someObj = {
one: 123,
two: 345
};
var key = one;
delete someObj[key];
console.log(someObj); // prints { two: 345 }


Documentation:




[#79555] Thursday, March 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
skyler

Total Points: 646
Total Questions: 119
Total Answers: 96

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
;