如何搜索objectsreact.jsjavascript?

How to search objects react.js javascript?

感谢您的阅读。

我需要按语言或大洲对国家/地区进行排序,用户select是他想要的按钮选项。

countries 是每个国家的 object 个数组,其中包含:

如果用户 select 例如大陆并在输入“es”中输入所有结果相关的白色内容亚洲一起列在一个组中并且不要在每个大陆中重复大陆标题,我需要相同与语言。
这是我的代码:

const CountrySearch = ({countries}) => {
    const [searchTerm, setSearchTerm] = useState("");
    console.log(countries)
    return (
        <div className="search">
            <h1>Country Search</h1>
            <span> Some random text </span>
            <div className="searchResults">
                <input type="text" placeholder="Search country..." onChange={event => {
                    setSearchTerm(event.target.value)
                }}/>
                <div className="groupBy">
                    <h2> Group by: </h2>
                    <div>
                        <button> Continent </button>
                        <button> Language </button>
                    </div>
                </div>

                <div>
                    {countries.filter((val) => {
                        if (searchTerm === "") {
                            return ""
                        } else if (val.name.toLowerCase().includes(searchTerm.toLowerCase())){
                            return val
                        }
                    }).map((val, key) => {
                        return (
                            <div key={key}>
                                <h2> {val.continent.name} </h2> 
                                <div className="countryInfo">
                                    <div>
                                        <span>{val.emoji}</span>
                                        <h3> {val.name} </h3>
                                    </div>
                                    <p> Capital: {val.capital} </p>
                                    <p> Currency: {val.currency} </p>
                                </div>
                            </div>
                        )
                    })
                    }
                </div>
            </div>
        </div>
    )
}
export default CountrySearch;

首先过滤数据,然后使用 reduce 按大洲分组,然后遍历数组并创建所需的 JSX。

您可以参考下面的代码片段(在输入框中输入“s”):

const countries = [
  {
    name: "India",
    continent: { name: "Asia" },
    languages: [{ name: "Hindi" }, { name: "English" }, { name: "Marathi" }],
  },
  {
    name: "Sri Lanka",
    continent: { name: "Asia" },
    languages: [{ name: "Srilankan" }, { name: "Tamil" }],
  },
  {
    name: "Spain",
    continent: { name: "Europe" },
    languages: [{ name: "Spanish" }, { name: "English" }],
  },
  {
    name: "Slovakia",
    continent: { name: "Europe" },
    languages: [{ name: "English" }],
  },
];

function App() {
  const [searchTerm, setSearchTerm] = React.useState("");

  return (
    <div>
      <input
        type="text"
        value={searchTerm}
        onChange={({ target }) => setSearchTerm(target.value)}
      />
      {Object.entries(
        countries
          .filter((c) =>
            c.name.toLowerCase().includes(searchTerm.toLowerCase())
          )
          .reduce((res, c) => {
            if (!res[c.continent.name]) {
              res[c.continent.name] = [];
            }
            res[c.continent.name].push(c);
            return res;
          }, {})
      ).map(([continent, countries]) => (
        <ul key={continent}>
          <li>
            <div>{continent}</div>
            <ul>
              {countries.map(({ name, languages }) => (
                <li key={name}>
                  <div>{name}</div>
                  <ul>
                    {languages.map(({ name }) => (
                      <li key={name}>{name}</li>
                    ))}
                  </ul>
                </li>
              ))}
            </ul>
          </li>
        </ul>
      ))}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>

以下是上述片段中执行分组的代码部分:

Object.entries(
  countries
    .filter((c) => c.name.toLowerCase().includes(searchTerm.toLowerCase()))
    .reduce((res, c) => {
      if (!res[c.continent.name]) {
        res[c.continent.name] = [];
      }
      res[c.continent.name].push(c);
      return res;
    }, {})
);