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

101
Visualizações
Search an element in an array component of a json file using JS

I am running this code snipped in React to search if there is a match with the user's input. The json file goes as follows:

{
  "first":{
    "name": "Michael Jordan",
    "id": "mj"
    "image": ".../icon.png",
    "tags": [
      "Sportsman",
      "Tall",
      "Famous",
      "something",
      "etc"
    ]
  },
  "second":{
    "name": "Paul White",
    "id": "pw"
    "image": ".../icon.png",
    "tags": [
      "Engineer",
      "Small",
      "Famous",
      "Another characteristic",
      "likes apples"
      "something",
      "etc2"
    ]
  }
}

and here is the search function I made to search through all the names and tags if there is a matching "person", and afterwards display all the "people" that share the same tags or names

const [q, setQ] = useState("");

function main_char_search(searchProp) {
    const tagssearch = searchProp[0].tags && Object.keys(searchProp[0].tags);
    return searchProp.filter(
      (new_items) => new_items.name.toLowerCase().indexOf(q) > -1 ||
      tagssearch.some((tagsearch)=>new_items[tagsearch].toString().toLowerCase().indexOf(q)) > -1
    );
  }

the trick is that the array that contains the tags varies in size sometimes.

The input is supposed to look like the JSON file. After all it is the result after fetching the JSON file using "fetch".

const [loadChar, setLoadChar] = useState([]);

fetch('./data/fakeData.json')
  .then((res) => return res.json())
  .then((data) => {
    //more code
    setLoadChar(all_the_characters_from_json_file);
  })

and I call the function with:

<APageForCharacters inputInfo={main_char_search(loadChar)} />

Here is the errors that this code generates:
TypeError cannot read properties of undefined (reading 'tags')
Uncaught (in ... promise)

Note: the code runs perfectly if I try to search through the names and other individual components.
Note 2: the tagssearch variable is storing the values of tags as their index number, so the code is wrong from there, but I am still struggling to find the best solution with best time complexity.
Hopefully I am not missing any required information.

about 4 years ago · Juan Pablo Isaza
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