Javascript 在 json 内搜索

Javascript searching within json

假设我有一个看起来像这样的 JSON 对象,名为 "prices"

"Scrap Metal": {
            "defindex": [
                5000
            ],
            "prices": {
                "3": {
                    "Tradable": {
                        "Craftable": {
                            "0": {
                                "currency": "keys",
                                "value": 432,
                                "last_update": 1425334795,
                                "difference": 3491.64
                            }
                        }
                    }
                },
                "6": {
                    "Tradable": {
                        "Craftable": {
                            "0": {
                                "currency": "metal",
                                "value": 0.11,
                                "last_update": 1336410088,
                                "difference": 0
                            }
                        }
                    }
                }
            }
        },

这样继续下去,结构相似但值不同。我想搜索 defindex: 5000 值,然后从 6 中获取 value。换句话说,如果我通过搜索 defindex 知道它在代码中的位置,我会调用 "name".prices[6].Tradable.Craftable[0].value.

我曾尝试为此使用 underscore.js,但没有成功。我的代码是: _.where(prices, { defindex: '5000' });

如有任何帮助,我们将不胜感激。谢谢!

我会使用 #find,它允许您使用一个函数,迭代每个 key/value 对,其中值将是顶部键指向的值。

_.find(prices, function(value, key) { 
  return (value.defindex == "5000")
})

由于您可能有多种可能的查询并且您正在使用下划线,因此您可能会喜欢 https://github.com/davidgtonge/underscore-query,因为它提供了类似于 Mongo 的查询语法: