Iterate through Nested JavaScript Objects [duplicate] Iterate through Nested JavaScript Objects [duplicate] javascript javascript

Iterate through Nested JavaScript Objects [duplicate]


You can create a recursive function like this to do a depth-first traversal of the cars object.

var findObjectByLabel = function(obj, label) {    if(obj.label === label) { return obj; }    for(var i in obj) {        if(obj.hasOwnProperty(i)){            var foundLabel = findObjectByLabel(obj[i], label);            if(foundLabel) { return foundLabel; }        }    }    return null;};

which can be called like so

findObjectByLabel(car, "Chevrolet");


In case you want to deeply iterate into a complex (nested) object for each key & value, you can do so using Object.keys(), recursively:

const iterate = (obj) => {    Object.keys(obj).forEach(key => {    console.log(`key: ${key}, value: ${obj[key]}`)    if (typeof obj[key] === 'object') {            iterate(obj[key])        }    })}

REPL example.


𝗗𝗲𝗮𝗱-𝘀𝗶𝗺𝗽𝗹𝗲 𝘄𝗶𝘁𝗵 𝟯 𝘃𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀, 𝟵 𝗹𝗶𝗻𝗲𝘀, 𝗮𝗻𝗱 𝗻𝗼 𝗿𝗲𝗰𝘂𝗿𝘀𝗶𝗼𝗻

function forEachNested(O, f, cur){    O = [ O ]; // ensure that f is called with the top-level object    while (O.length) // keep on processing the top item on the stack        if(           !f( cur = O.pop() ) && // do not spider down if `f` returns true           cur instanceof Object && // ensure cur is an object, but not null            [Object, Array].includes(cur.constructor) //limit search to [] and {}        ) O.push.apply(O, Object.values(cur)); //search all values deeper inside}

To use the above function, pass the array as the first argument and the callback function as the second argument. The callback function will receive 1 argument when called: the current item being iterated.

(function(){"use strict";var cars = {"label":"Autos","subs":[{"label":"SUVs","subs":[]},{"label":"Trucks","subs":[{"label":"2 Wheel Drive","subs":[]},{"label":"4 Wheel Drive","subs":[{"label":"Ford","subs":[]},{"label":"Chevrolet","subs":[]}]}]},{"label":"Sedan","subs":[]}]};var lookForCar = prompt("enter the name of the car you are looking for (e.g. 'Ford')") || 'Ford';lookForCar = lookForCar.replace(/[^ \w]/g, ""); // incaseif the user put quotes or something around their inputlookForCar = lookForCar.toLowerCase();var foundObject = null;forEachNested(cars, function(currentValue){    if(currentValue.constructor === Object &&      currentValue.label.toLowerCase() === lookForCar) {        foundObject = currentValue;    }});if (foundObject !== null) {    console.log("Found the object: " + JSON.stringify(foundObject, null, "\t"));} else {    console.log('Nothing found with a label of "' + lookForCar + '" :(');}function forEachNested(O, f, cur){    O = [ O ]; // ensure that f is called with the top-level object    while (O.length) // keep on processing the top item on the stack        if(           !f( cur = O.pop() ) && // do not spider down if `f` returns true           cur instanceof Object && // ensure cur is an object, but not null            [Object, Array].includes(cur.constructor) //limit search to [] and {}        ) O.push.apply(O, Object.values(cur)); //search all values deeper inside}})();