javascript - 搜索复杂的 JSON 数据以匹配键值

标签 javascript json loops nested-loops

我很难解决这个问题。我搜索并找到了一些类似问题的答案,但所有示例中的 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进行匹配。因此,在本例中 377355 是匹配的。对于所有匹配的附件,我需要获取其完整缩略图 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/

相关文章:

javascript - 无法再从 webstorm 调试 javascript

javascript - 通过引用 javascript 中的函数来循环遍历数组

javascript - 访问等于 javascript 中特定值的 JSON 属性

Python for 循环声明和行为

arrays - 扩展每个列单元格的列单元格

c# - 在 WPF 项目中,如何初始化窗口和控件,然后跳转到主循环?

javascript - Fabric JS 解析器的 SVG 文本对齐问题

javascript - Backbone + FileUpload + Java Servlet + Jackson - Base64 = 噩梦?

json - 如何更改json key :value

javascript - 如何将 x-www-form-urlencoded 字符串转换为 JSON?