I want to search only in name
property of the list of json objects. This is the json array -
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. The search function is the following -
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:
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()
.
This will return an array containing all elements that pass the condition.
const searchFilter = "Bazaar Cafe"
const filtered = combinedArr.filter(item => item.name === searchFilter);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.