2017-03-27 177 views
1

我分析了一个XML文件并检索了以下JSON对象。 问题是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); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我想通过对象进行迭代,每一个 “匹配” 的孩子。类似这样的:

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

在此先感谢您。

+0

'value.app.mapped.match' – Weedoze

回答

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

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

它会给你预期的结果。

0

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

+0

没有破折号在哪里?你能更清楚吗? – Weedoze

+0

@AppRoyale它现在工作正常吗? – Weedoze

+0

@AppRoyale请勿尝试更新您的问题。这会导致对第一个想法的误解。 +检查数组,你会看到最后一个对象具有'regex'和'configuration'作为属性而不是'name'和'url' – Weedoze