Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
How to search objects react.js javascript?

Thanks for your time reading.

I need to sort countries by Language or Continent, the user selects the option he wants in the buttons.

countries is an array of objects of each country that contain:

  • languages is an array of objects, because each country can have more than one language
  • continent is an object with the continent name
    Complete example(countries array content): https://github.com/gonzaloramosf/countries

If the user select for example continents and types in the input "es" all the results related whit content Asia listed together in a group and do not repeat the continent title in each one, same i need with languages.
This is my code:

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;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First filter the data and then group it by continent using reduce and then loop over the arrays and create the desired JSX.

You can refer the snippet below (type "s" in the input box):

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>

Following is the portion of code from the above snippet that does the grouping:

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;
    }, {})
);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda