【问题标题】:Javascript: ForEach over sub objects [duplicate]Javascript:子对象上的 ForEach [重复]
【发布时间】:2016-05-22 22:05:22
【问题描述】:

我正在使用 forEach 来遍历 javascript 中的对象。在我尝试迭代子字段之前,它按预期工作。我将如何使用 forEach 迭代字段和子字段?以下是代码的 sn-p 以及预期和实际结果。任何帮助将不胜感激:)

  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]);
  });

预期:

-乔

-污垢

-沙子

结果:

-乔

-污垢

-未定义

【问题讨论】:

    标签: javascript json loops foreach undefined


    【解决方案1】:

    您可以在临时对象的帮助下迭代拆分的属性。

    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>');
    });

    【讨论】:

    • 工作就像一个魅力。
    猜你喜欢
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 2016-10-31
    • 2022-11-30
    • 1970-01-01
    相关资源
    最近更新 更多