【问题标题】:Search Array of Objects including child nested objects搜索对象数组,包括子嵌套对象
【发布时间】:2016-08-20 01:05:02
【问题描述】:

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

目前我有:

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 小时一直在拔头发!

【问题讨论】:

  • 你不需要自己写这个吧?你看过 lodash 之类的库吗?
  • 为了清楚起见,你的意思是你想要一个你可以调用的函数,比如search(theOffices,'msn'),并让它返回一个包含“msn”作为值的所有对象的数组任何深度的属性或其任何“子”对象上的属性值?

标签: javascript jquery arrays object search


【解决方案1】:

您可以使用数组 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 2020-06-11
    • 2017-01-28
    • 1970-01-01
    相关资源
    最近更新 更多