Created
May 21, 2022 08:19
-
-
Save adarsh-chakraborty/7fd519cbabf09d8a32f475f7a4f5e8d8 to your computer and use it in GitHub Desktop.
Loop through nested objects in JS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Solution by Suraj Yadav */ | |
let obj = { | |
name: "adarsh", | |
id: 98, | |
roll: "sfd", | |
num2: { | |
name: "num_adarsh2", | |
id: 98, | |
roll: "sfd", | |
num3: { | |
name: "num_Adarsh3" | |
}, | |
}, | |
} | |
let newlist = []; | |
const myFun = (DATA, myKey) => { | |
for(let key in DATA){ | |
if(key === myKey){ | |
newlist.push(DATA[key]); | |
console.log(DATA[key]); | |
return; | |
} | |
if(typeof(DATA[key]) == 'object'){ | |
myFun(DATA[key], myKey); | |
} | |
} | |
} | |
myFun(obj, 'num2'); | |
console.log(newlist); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment