如何在对象数组中搜索特定的匹配属性值?

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;
  }
评论
  • Max
    Max 回复

    Just use filter like so:

    const filtered = combinedArr.filter(({ name }) => name.includes("My name"));
    
  • 莫i相忘
    莫i相忘 回复

    You can use array filter().

    const searchFilter = "Bazaar Cafe"
    
    
    const filtered = combinedArr.filter(item => item.name === searchFilter);
    
  • jvitae
    jvitae 回复
    let 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",
      },
    ];
    
    function filterByName(passedName, arr){
       return arr.filter(el => el.name == passedName)
    }
    
    let result = filterByName("Bazaar Cafe", combinedArr);
    
    console.log(result);