2017-03-27 527 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