[英]How to search for a particular matching property value inside an array of objects?
I want to search only in name
property of the list of json objects.我只想在 json 对象列表的name
属性中搜索。 This is the json array -这是 json 阵列 -
combinedArr = [
{
lat: "36.1152",
locality: "Worth Avenue, Unit A",
long: "117.521",
name: "Bazaar Cafe",
postal_code: "20619",
street_no: "45250",
},
{
lat: "31.21",
locality: "Ambey Mantion",
long: "119.7",
name: "Ashley's Cafe",
postal_code: "29087",
street_no: "1B",
},
];
This is the search function, this search function search in all properties of the objects but I just want it to search only in name
property and return list of search results.这是搜索 function,此搜索 function 搜索对象的所有属性,但我只希望它仅在name
属性中搜索并返回搜索结果列表。 The search function is the following -搜索 function 如下——
function findCaliforniaCafes(searchTerm) {
const filterByValue = (combinedArr, string) => {
return combinedArr.filter((o) =>
Object.keys(o).some((k) =>
o[k].toLowerCase().includes(string.toLowerCase())
)
);
};
const result = searchTerm
? filterByValue(combinedArr, searchTerm)
: combinedArr;
return result;
}
Just use filter
like so:只需像这样使用filter
:
const filtered = combinedArr.filter(({ name }) => name.includes("Ashley"));
const combinedArr = [{lat:"36.1152",locality:"Worth Avenue, Unit A",long:"117.521",name:"Bazaar Cafe",postal_code:"20619",street_no:"45250",},{lat:"31.21",locality:"Ambey Mantion",long:"119.7",name:"Ashley's Cafe",postal_code:"29087",street_no:"1B",}]; const filtered = combinedArr.filter(({ name }) => name.toLowerCase().includes(searchTerm)); console.log(filtered);
.as-console-wrapper { max-height: 100%;important: top; auto; }
You can use array filter()
.您可以使用数组filter()
。
This will return an array containing all elements that pass the condition.这将返回一个包含所有通过条件的元素的数组。
const searchFilter = "Bazaar Cafe"
const filtered = combinedArr.filter(item => item.name === searchFilter);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.