Ask Your Question
2

Is there a way to traverse through properties of embedded objects without utilizing nested for-loops?

asked 2023-07-11 09:51:52 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-11 10:12:01 +0000

bukephalos gravatar image

Yes, you can use the Object.keys() and Object.values() methods to traverse through the properties of embedded objects without using nested for-loops. Here is an example:

const obj = {
  a: 1,
  b: {
    c: 2,
    d: 3
  }
};

// Get the keys of the outer object
const keys1 = Object.keys(obj);

// Loop through the keys and check if the value is an object
keys1.forEach(key1 => {
  const value1 = obj[key1];
  if (typeof value1 === 'object' && value1 !== null) {

    // Get the keys of the inner object
    const keys2 = Object.keys(value1);

    // Loop through the keys and get the values
    keys2.forEach(key2 => {
      const value2 = value1[key2];
      console.log(key1, key2, value2);
    });
  }
});

Output:

b c 2
b d 3
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-11 09:51:52 +0000

Seen: 8 times

Last updated: Jul 11 '23