我解析了一个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);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
我想遍历该对象并提取每个“匹配”子项。像这样:
return [
{
name: 'Foo 1',
url: 'Bar 1'
},
[...]
]
提前谢谢你。
答案 0 :(得分: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>
它会给你预期的结果。
答案 1 :(得分: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']);
&#13;