繁体   English   中英

搜索对象数组,包括子嵌套对象

[英]Search Array of Objects including child nested objects

我希望在带有嵌套对象的数组上搜索任何值,然后返回在其中找到的对象以将其放入新数组中。

目前我有:

var json = {
    'offices': [{
        "home_id": "1",
        "price": "925",
        "sqft": "1100",
        "num_of_beds": "2",
        "num_of_baths": "2.0",
        "types": {
            "0": "Internet",
            "1": "msn",
            "2": "aol"
        }
    }, {
        "home_id": "2",
        "price": "1425",
        "sqft": "1900",
        "num_of_beds": "4",
        "num_of_baths": "2.5",
        "types": {
            "0": "Internet",
            "1": "google",
            "2": "virgin"
        }
    }]
}

var theOffices = json.offices;

var result = $.grep(theOffices, function (h) {
  return h.home_id == 1
    && h.price == 925
});

console.log(result)

我可以使用$ .grep进行搜索,如上所示,但是,该搜索仅在第一个对象上进行,而不是在嵌套对象上进行搜索…即我将如何扩展$ .grep的使用范围以遍历“类型”-例如得到“ MSN”?

请帮助:) :)过去6个小时一直在拔头发!

您可以使用数组filter()完成此操作。 查看以下内容:

 var json = { 'offices': [{ "home_id": "1", "price": "925", "sqft": "1100", "num_of_beds": "2", "num_of_baths": "2.0", "types": { "0": "Internet", "1": "msn", "2": "aol" } }, { "home_id": "2", "price": "1425", "sqft": "1900", "num_of_beds": "4", "num_of_baths": "2.5", "types": { "0": "Internet", "1": "google", "2": "virgin" } }, { "home_id": "1", "price": "925", "sqft": "1980", "num_of_beds": "6", "num_of_baths": "9.5", "types": { "0": "InterNope", "1": "google", "2": "virgin" } } ] } var theOffices = json.offices; var results = theOffices.filter( function(f) { return f.home_id == "1" && f.price == "925"; }); console.log("res"); console.log(results); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM