Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!