在json中搜索Javascript

Javascript searching within json

本文关键字:Javascript 搜索 json      更新时间:2023-09-26

假设我有一个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,它允许您使用函数,迭代每个键/值对,其中值将是顶部键指向的。

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

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