Skip to content

Instantly share code, notes, and snippets.

@adarsh-chakraborty
Created May 21, 2022 08:19
Show Gist options
  • Save adarsh-chakraborty/7fd519cbabf09d8a32f475f7a4f5e8d8 to your computer and use it in GitHub Desktop.
Save adarsh-chakraborty/7fd519cbabf09d8a32f475f7a4f5e8d8 to your computer and use it in GitHub Desktop.
Loop through nested objects in JS.
/* 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