過濾列表中包含列表的對象的最有效方法是什麼?我一直在看下劃線的_.filter函數,但這需要使用數組並返回數組。使用列表篩選對象列表 - Javascript
我想採取一個對象,並通過某個詞過濾它。
例如,我將如何過濾:
[
{level: "Title 1", details: [
{real: "There we go", fake: "THERE_WE_GO"},
{real: "Where is it", fake: "WHERE_IS_IT"},
{real: "The dog jumped", fake: "THE_DOG_JUMPED"},
] },
{level: "Title 2", details: [
{real: "There it is", fake: "THERE_IT_IS"},
{real: "Car is flying", fake: "CAR_IS_FLYING"},
{real: "Driving is fun", fake: "DRIVING_IS_FUN"}
] },
{level: "Title 2", details: [
{real: "There he is", fake: "THERE_WE_GO"},
{real: "Where is the dog", fake: "WHERE_IS_THE_DOG"},
{real: "The dog died", fake: "THE_DOG_DIED"},
{real: "I am tired", fake: "I_AM_TIRED"},
]}
];
由單詞 「the」
,使其返回
[
{level: "Title 1", details: [
{real: "There we go", fake: "THERE_WE_GO"},
{real: "The dog jumped", fake: "THE_DOG_JUMPED"},
] },
{level: "Title 2", details: [
{real: "There it is", fake: "THERE_IT_IS"},
] },
{level: "Title 2", details: [
{real: "There he is", fake: "THERE_WE_GO"},
{real: "Where is the dog", fake: "WHERE_IS_THE_DOG"},
{real: "The dog died", fake: "THE_DOG_DIED"},
]}
];
注意,當這個詞過濾器 「的」我還想保留任何有「the」這個詞作爲其中的一部分的詞,例如「there」......我只是去檢查單詞「the」是否在「the」的對象的「真實」索引中細節的數組。
這不是一個對象,而是一個對象數組。因此,下劃線過濾對你來說工作得很好。您當然需要編寫過濾功能。你有沒有做過任何可以顯示代碼的嘗試? –
ES5中有一個內置的[* filter *](http://ecma-international.org/ecma-262/5.1/#sec-15.4.4.20),爲什麼你需要這樣的underscore.js? – RobG