looping through an object (tree) recursively
You're looking for the for...in
loop:
for (var key in foo)
{
if (key == "child")
// do something...
}
Be aware that for...in
loops will iterate over any enumerable properties, including those that are added to the prototype of an object. To avoid acting on these properties, you can use the hasOwnProperty
method to check to see if the property belongs only to that object:
for (var key in foo)
{
if (!foo.hasOwnProperty(key))
continue; // skip this property
if (key == "child")
// do something...
}
Performing the loop recursively can be as simple as writing a recursive function:
// This function handles arrays and objects
function eachRecursive(obj)
{
for (var k in obj)
{
if (typeof obj[k] == "object" && obj[k] !== null)
eachRecursive(obj[k]);
else
// do something...
}
}
recursive looping a object tree
You could use a function which takes the actual level and returns the callback for the array method.
Inside, the callback displays the key and call the function again with an increased level for next iteration.
function iter(level) { return function (node) { console.log('node', level, node.key); (node.children || []).forEach(iter(level + 1)); };}
var tree = [{ key: "parent1", id: "001", children: [{ key: "B", id: "002", children: [{ key: "C", id: "003", children: [{ key: "D", id: "004", children: [] }] }] }] }, { key: "parent2", id: "002", children: [{ key: "B", id: "002", children: [{ key: "C", id: "003", children: [{ key: "D", id: "004", children: [] }] }] }] }];
tree.forEach(iter(0));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Recursively looping through an object to build a property list
I made a FIDDLE for you. I am storing a stack
string and then output it, if the property is of primitive type:
function iterate(obj, stack) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property], stack + '.' + property);
} else {
console.log(property + " " + obj[property]);
$('#output').append($("<div/>").text(stack + '.' + property))
}
}
}
}
iterate(object, '')
Update: 17/01/2019
There used to be a different implementation, but it didn't work. See
this answer
for a prettier solution
Recursive loop through Javascript Object
You have a couple of issues; you should be traversing over the object, not its keys, and you should be checking if key === 'e'
, not target[key] !== 'e'
. Also, you should check that target[key]
is an object before attempting to traverse it:
const myObject = {
x: {
y: {
z: {
e: 'ddfg'
}
}
}
};
function traverse(target) {
for (const key in target) {
if (key !== 'e' && typeof target[key] === 'object') {
traverse(target[key]);
} else {
console.log(key, target[key]);
}
}
}
traverse(myObject);
How to iterate recursively over all children in nested objects
You are passing child which is an object and that is not iterable, you have to pass it's children. You can try checking if child having children array and then iterate children.
function selectActivePage(node) {
for (let child of node) {
child.folded = false;
if(child.children && Array.isArray(child.children) && child.children.length > 0)
selectActivePage(child.children)
}
};
Recursively looping over an array of objects using a for loop
I figured out the problem I was having! I had to assign the value to a temp variable, then return it if it was not undefined.
if (Array.isArray(tree)) {
for (let item of tree) {
let tmp = searchTreeForNode(item, nodeUuid);
if (tmp !== undefined) {
return tmp;
}
}
}
Related Topics
Change Values in Array When Doing Foreach
How to Detect a Textbox's Content Has Changed
Controlling Fps with Requestanimationframe
How to Change Href of <A> Tag on Button Click Through JavaScript
How to Get the Mouse Position Without Events (Without Moving the Mouse)
Axios Posting Params Not Read by $_Post
How to Sort Elements by Numerical Value of Data Attribute
How to Change CSS :Root Color Variables in JavaScript
How Send a Form with JavaScript When Input Name Is "Submit"
Angularjs: Better Way to Watch for Height Change
Get Average Color of Image via JavaScript
Switch Statement for Greater-Than/Less-Than
Difference Between Textcontent VS Innertext
JavaScript Require() Function Giving Referenceerror: Require Is Not Defined
JavaScript "This" Pointer Within Nested Function
Jquery Ajax Call to PHP Script with JSON Return