我很难解决这个问题。我搜索并找到了一些类似问题的答案,但所有示例中的 JSON 数据都太简单了。我的更复杂。
我有一个正在循环的数字数组。对于每个循环,我需要将数字与 JSON 数据进行匹配,以找到匹配的条目,然后从该条目中获取特定的键值。
这是我的数组的示例:
结果 = [377, 375, 373, 353, 355]
这是我的 JSON 数据的示例:
{
"count": 10,
"posts": [
{
"title": "Title of Post",
"attachments": [
{
"id": 377,
"images": {
"full": {
"url": "http://example.com/images/foo.jpg",
"width": 800,
"height": 600
},
"thumbnail": {
"url": "http://example.com/images/foo_thumb.jpg",
"width": 150,
"height": 150
}
}
},
{
"id": 355,
"images": {
"full": {
"url": "http://example.com/images/bar.jpg",
"width": 800,
"height": 600
},
"thumbnail": {
"url": "http://example.com/images/bar_thumb.jpg",
"width": 150,
"height": 150
}
}
}
]
},
// 9 more posts...
]
}
对于结果
中的每个数字,我需要将其与每个posts.attachments.id
进行匹配。因此,在本例中 377
和 355
是匹配的。对于所有匹配的附件,我需要获取其完整
和缩略图
URL。
就像我说的,我已经找到了可能的解决方案,但示例数据只有 1-2 层深。我无法完全理解这个特定场景所需的循环。
最佳答案
var urls = [];
var att = posts.attachments;
for (var i = 0; i < results.length; i++) {
var id = results[i];
for (var j = 0; j < att.length; j++) {
if (att[j].id == id) {
urls.push({
id: id,
full: att[j].images.full.url,
thumbnail: att[j].images.thumbnail.url
});
break;
}
}
}
关于javascript - 搜索复杂的 JSON 数据以匹配键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23375730/