【问题标题】:Iterate through JSON-Object Array遍历 JSON-Object 数组
【发布时间】:2017-03-27 12:07:49
【问题描述】:

我解析了一个 XML 文件并检索了以下 JSON 对象。 问题是 json 中有破折号,这会导致遍历对象时出现问题。不幸的是,我无法摆脱它们。

$(function() {
  let json = JSON.parse('{"app-app":{"$":{},"notneeded":"123","mapped":{"$":{},"match-match":[{"$":{},"name":"Foo 1","url":"/Bar 1"},{"$":{},"name":"Foo 2","url":"/Bar 2"},{"$":{},"name":"Foo 3","url":"Bar 3"}]},"Nothing":"123"}}');

  var foo = Object.keys(json['app-app']['mapped']['match-match']).length;
  for (var i = 0; i < foo; i++) {
    console.log(json['app-app']['mapped']['match-match'][i].name);
    console.log(json['app-app']['mapped']['match-match'][i].url);
  }
});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

我想遍历对象并提取每个“匹配”的孩子。像这样的:

return [
            {
                name: 'Foo 1',
                url:  'Bar 1'
            },
            [...]
       ]

提前谢谢你。

【问题讨论】:

  • value.app.mapped.match

标签: javascript arrays json loops parsing


【解决方案1】:

您可以简单地使用 Array.prototype.map() 来遍历您的 json 数组并返回您的自定义结构,如下所示:

$(function() {
  let json = JSON.parse('{"app-app":{"$":{},"notneeded":"123","mapped":{"$":{},"match-match":[{"$":{},"name":"Foo 1","url":"/Bar 1"},{"$":{},"name":"Foo 2","url":"/Bar 2"},{"$":{},"name":"Foo 3","url":"Bar 3"}]},"Nothing":"123"}}');


  var result = json['app-app']['mapped']['match-match'].map(function(item) {
    return {
      "name": item.name,
      "url": item.url
    };
  });
  console.dir(result);

});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

它会给你预期的结果。

【讨论】:

    【解决方案2】:

    let json = JSON.parse('{"app":{"$":{},"notneeded":"123","mapped":{"$":{},"match":[{"$":{},"name":"Foo 1","url":"/Bar 1"},{"$":{},"name":"Foo 2","url":"/Bar 2"},{"$":{},"regex":"Foo 3","configuration":"Bar 3"}]},"Nothing":"123"}}');
    console.log(json['app']['mapped']['match']);

    【讨论】:

    • @AppRoyale 不要尝试更新您的问题。这会导致对第一个想法的误解。 + 检查数组,你会看到最后一个对象有regexconfiguration 作为属性,而不是nameurl
    猜你喜欢
    • 2016-05-27
    • 2011-02-05
    • 2018-11-29
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    相关资源
    最近更新 更多