所以我有一個字串陣列 = ["ethan" , "kathrine"]
我有一個具有多個屬性的物件,但我只對這些屬性感興趣name,并且description
例如
arr = [
{name: "ethaniel" , description: "strong" , age: 200} ,
{name: "kathrine" , description: "beautiful" , age: 220},
{name: "zack" , description: "he loves kathrine" , age: 133},
{name: "ethan" , description: "he loves kathrine" , age: 133},
{name: "bob" , description: "he loves trucks" , age: 133}
]
結果陣列應該是
arr = [
{name: "ethaniel" , description: "strong" , age: 200} ,
{name: "kathrine" , description: "beautiful" , age: 220},
{name: "zack" , description: "he loves kathrine" , age: 133},
{name: "ethan" , description: "he loves kathrine" , age: 133}
]
因為他們每個人的名字或描述中都包含 ethan 或 kathrine
我的想法是這樣做
filteredArry = arr.filter(i => {return i.name.some('a') || i.description.includes('a')})
或者類似的東西
我只是不明白,如果我必須使用 some 或 contains 以及如何在 include/some 方法中包含具有關鍵字的陣列的所有內容
uj5u.com熱心網友回復:
Array#some:
測驗陣列中是否至少有一個元素通過了提供的函式實作的測驗。如果在陣列中找到一個元素,提供的函式為其回傳真值,則回傳真值;否則回傳false。它不會修改陣列。
Sring#includes:
執行區分大小寫的搜索以確定是否可以在另一個字串中找到一個字串,并根據需要回傳 true 或 false。
因此,在filter迭代,你需要檢查,如果任何的子串的或者是在與name或description:
const
arr = [ {name: "ethaniel" , description: "strong" , age: 200} , {name: "kathrine" , description: "beautiful" , age: 220}, {name: "zack" , description: "he loves kathrine" , age: 133}, {name: "ethan" , description: "he loves kathrine" , age: 133}, {name: "bob" , description: "he loves trucks" , age: 133} ],
subStrs = ["ethan" , "kathrine"];
const filteredArry = arr.filter(({ name, description }) =>
subStrs.some(subStr => name.includes(subStr) || description.includes(subStr))
);
console.log(filteredArry);
uj5u.com熱心網友回復:
分解使這更簡單。當名稱或描述值包含給定子字串之一時,過濾謂詞為真。
// test if a person's name or description contains any substring in the substrings array
const personMatch = (personObject, substrings) => {
return includesSome(personObject.name, substrings) ||
includesSome(personObject.description, substrings)
};
// test if a string contains any substrings
const includesSome = (string, substrings) => {
return substrings.some(substring => caseInsensitiveIncludes(string, substring))
};
// maybe useful. decomposing into smaller functions lets you
// add features and retest more easily
const caseInsensitiveIncludes = (string, substring) => {
return string.toLowerCase().includes(substring.toLowerCase())
}
const people = [{
name: "ethaniel",
description: "strong",
age: 200
},
{
name: "sally",
description: "ethan is her friend",
age: 300
}
// ...
];
const names = ["Ethan", "Kathrine"];
const somePeople = people.filter(person => personMatch(person, names));
console.log(somePeople);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362147.html
標籤:javascript
