簡體   English   中英

如何在 javascript 數組中搜索關鍵字?

[英]How can i search for keywords in a javascript array?

我正在 React 項目中處理搜索輸入組件。 我有一組對象,當有人單擊搜索時,我正在映射這些對象。 目標是獲取用戶輸入並使用它在數組中找到類似的東西。 現在我必須搜索確切的項目才能使其工作。 例如,如果我搜索“二手車出售”,它將顯示該對象,但如果我刪除任何單詞/字母,則不會顯示。 有沒有辦法只查找關鍵字? 謝謝!

function Search() {
  const items = [
    {
      title: "Used Car for sale",
      description: "I am selling a used 2003 Honda Civic. Works well.",
      price: "$1000",
    },
    {
      title: "computer for sale",
      description: "Selling a brand new Dell computer",
      price: "$800",
    },
    {
      title: "Used phone for sale",
      description: "I am selling my iphone 1",
      price: "$400",
    },
  ];

 
  const [text, setText] = useState("");

 

  const searchPosts = () => {
    items.map((item) => {
      if (item.title === text) {
        console.log(item);
      } else {
        console.log("item not found");
      }
    });
  };
  return (
    <>
      <h1>{posts[0].title}</h1>
      <div className="input-group mb-3 main-search">
        <input
          type="text"
          className="form-control "
          placeholder="Search for anything..."
          aria-label="Recipient's username"
          aria-describedby="button-addon2"
          onChange={(e) => setText(e.target.value)}
        />
        <div className="input-group-append">
          <button
            onClick={searchPosts}
            className="btn btn-outline-secondary main-search-button"
            type="button"
            id="button-addon2"
          >
            Search
          </button>
        </div>
      </div>
    </>
  );
}

您可以在標題字段中拆分您的單詞並檢查您提供的關鍵字

在第一個示例中,返回 2 條記錄,因為在關鍵字字符串中,兩個單詞都包含在記錄中

在第二個中,所有記錄都返回,因為所有元素中都存在銷售

 const items = [{ title: "Used Car for sale", description: "I am selling a used 2003 Honda Civic. Works well.", price: "$1000", }, { title: "computer for sale", description: "Selling a brand new Dell computer", price: "$800", }, { title: "Used phone for sale", description: "I am selling my iphone 1", price: "$400", }, ]; function filterResults(list, keyword) { return list.filter(x => { const arr = x.title.toLowerCase().split(' '); return arr.some(y => keyword.toLowerCase().includes(y)) }); } console.log(filterResults(items, 'computer phone')) console.log(filterResults(items, 'computer'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM