Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda