0

I am using a forEach to iterate over a object in javascript. It works as expected until I try to iterate over a sub field. How would I go about iterating over fields and sub fields using forEach? Below is a snippet of code as well as expected and actual result. Any help would be appreciated :)

  const person = {
    first: 'Joe',
    last: 'Dirt',
    previous: {
      last: 'Sand',
    }
  };

  const attributes = [
      'first',
      'last',
      'previous.last' <-- Undefined. How do I access this?

    ];

  attributes.forEach(element => {
    console.log(person[element]);
  });

EXPECTED:

-Joe

-Dirt

-Sand

RESULT:

-Joe

-Dirt

-Undefined

emarel
  • 371
  • 7
  • 30

1 Answers1

1

You can iterate over the splitted attribute with the help of a temporary object.

var person = { first: 'Joe', last: 'Dirt', previous: { last: 'Sand', } },
    attributes = ['first', 'last', 'previous.last'];

attributes.forEach(function (element) {
    var obj = person;
    element.split('.').forEach(function (a) {
        obj = obj[a];
    });
    document.write(obj + '<br>');
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392