DEV Community

Abhi Raj
Abhi Raj

Posted on • Edited on

3 1

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

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay