2016-08-20 135 views
0

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

目前我有:

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'?

HELP PLEASE :) :)过去6小时一直拉出头发!

+0

你不需要这个写你自己,你呢?你有没有看过像lodash这样的图书馆? –

+0

只是要清楚,你的意思是你想要一个你可以调用的函数,比如'search(theOffices,'msn')',并且让它返回一个包含'msn'的所有对象的数组作为一个财产,或者它的任何“孩子”物体上的财产的价值,在任何深度? –

回答

0

您可以使用数组过滤器()来完成此操作。看看下面的:

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);