Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

Recursive loop through Javascript Object

So I can see the problem, I just don't know how to fix it. I've been all over the interwebz!

I don't know how you're supposed to move to the next entry in the object tree when the condition doesn't match. At the moment I'm just overloading the call stack.

const myObject = {
  x: {
    y: {
      z: {
        e: 'ddfg'
      }
    }
  }
};
const param = Object.keys(myObject);

function traverse(target) {
  for (const key in target) {
    if (target[key] !== 'e') {
      traverse(target[key]);
    } else {
      console.log(key, target[key]);
    }
  }
}

traverse(param);
question from:https://stackoverflow.com/questions/66055909/recursive-loop-through-javascript-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have a couple of issues; you should be traversing over the object, not its keys, and you should be checking if key === 'e', not target[key] !== 'e'. Also, you should check that target[key] is an object before attempting to traverse it:

const myObject = {
  x: {
    y: {
      z: {
        e: 'ddfg'
      }
    }
  }
};

function traverse(target) {
  for (const key in target) {
    if (key !== 'e' && typeof target[key] === 'object') {
      traverse(target[key]);
    } else {
      console.log(key, target[key]);
    }
  }
}

traverse(myObject);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...