DEV Community

Abhi Raj
Abhi Raj

Posted on • Edited on

How to Loop through nested JSON object in JavaScript recursively


in this video i have explained how you can traverse a nested JavaScript object with the help of recursion

here is the code

let obj = {
  name: "raj",
  roll: 892,
  id: {
    idName: "raj",
  },
  section: {
    sectionName: "raj",
    alias: {
      name: "raj",
    },
  },
};

let changeName = (obj) => {
  for (let i in obj) {
    if (obj[i] == "raj") {
      obj[i] == "abhishek";
    } else {
      changeName(obj[i]);
    }
  }
};

changeName(obj);

console.log(obj);

Enter fullscreen mode Exit fullscreen mode

result:


{
  name: 'raj',
  roll: 892,
  id: { idName: 'raj' },
  section: { sectionName: 'raj', alias: { name: 'raj' } }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
slimpython profile image
Abhi Raj

can i get some feedbacks?

Collapse
 
lexiebkm profile image
Alexander B.K.

I had ever found a case when I thought I needed to solve using recursion. That's why this topic is still interesting and can be useful.
But I am expecting a textual explanation with some codes that we can just copy-paste and try, evaluate in detail, rather than through a video.

Collapse
 
fyodorio profile image
Fyodor

100%, hate seeing just videos here, that’s a blogging platform in the end, not a YouTube proxy. So I come here to read and never open videos. That makes providing any feedback impossible unfortunately πŸ€·β€β™‚οΈ

Thread Thread
 
slimpython profile image
Abhi Raj

will keep that in mind from next time

Collapse
 
slimpython profile image
Abhi Raj

will keep that in mind from next time