I have an array something like this, I would like to iterate each element until they not have property "sub". How can I make it with javascript??? I don't know what number of "sub" they have.
var items = [
{ title: 'a' },
{ title: 'b', sub: [
{ title: 'ba' },
{ title: 'bb' }
] },
{ title: 'c', sub: [
{ title: 'ca', sub: [
{ title: 'caa' },
{ title: 'cba' }
] }
] }
];
-
so you want to make sub an empty array or get the array from sub? What have you tried so far?depperm– depperm2015年07月02日 15:57:02 +00:00Commented Jul 2, 2015 at 15:57
-
Iterate and do what with those items?dfsq– dfsq2015年07月02日 16:03:02 +00:00Commented Jul 2, 2015 at 16:03
-
What is the output you would like from the above? Do you want all the sub-items flattened into a single one-dimensional array of 8 objects, or do you just want all of them removed (ie. leave just an array of 'a', 'b', and 'c')?Nick F– Nick F2015年07月02日 16:35:18 +00:00Commented Jul 2, 2015 at 16:35
2 Answers 2
You can iterate your array recursively with something like this:
function iterateArray(array){
array.forEach(function(item){
var title = item.title;
console.log(title);
if(item.sub){
iterateArray(item.sub);
}
});
}
The iterateArray(items); output would be
a, b, ba, bb, c, ca, caa, cba
Sign up to request clarification or add additional context in comments.
2 Comments
Davide
Is it possible without jQuery??
RPallas
That's vanilla JavaScript, more info: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Generally the best way to loop through an arrays of arrays with an unknown nesting level and to do something on each item within the entire object is to use recursion.
function doThing(arr) {
if ( typeof(arr) == "object") {
for (var i = 0; i < arr.length; i++) {
doThing(arr[i]);
}
}
else {
//Do your thing with this item!
}
}
answered Jul 2, 2015 at 16:05
Daniel Hoffmann-Mitscherling
2,3691 gold badge18 silver badges23 bronze badges
Comments
lang-js