2016-08-20 212 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);