Skip to content
Advertisement

Finding values or objects in a json file with nested objects and passing the result object to child in Javascript and react

I am working on a react project where I am dealing with a json file of the following format.

{
   "trees":{
      "name":"a",
      "age":"9",
      "height":"10",
      "location":"park"
   },
   "cars":{
      "name":"b",
      "age":"30",
      "height":"10",
      "location":"park"
   },
   "bikes":{
      "name":"c",
      "age":"110",
      "height":"10",
      "location":"park"
   },.........................

The data from the json file (name , age, height , location) is shown in a table in a child component but now I am working on a functionality such that on whatsoever row of the table is clicked that rows data is shown in another component.

I am handling it such that whenever a row is clicked a function sends the name(eg. a or b or c) to the App.js and what I want to do is that find that values(name,age,height,location) corresponding to that name , store it and send those values to another child.

I am not able to traverse through this json file to find that values corresponding to the name and also dont have an idea how to store these multiple values to send it to a child.

This is what I tried to find the values(name , age , height , location) corresponding to the name:

const selected = Object.entries(Data).find(([key, { ...e }]) => {
  key.name === selectedId;
});
console.log(selected + "Selected");

and I am getting error.

Advertisement

Answer

You can try this code:

const obj = {
  "trees":{
     "name":"a",
     "age":"9",
     "height":"10",
     "location":"park"
  },
  "cars":{
     "name":"b",
     "age":"30",
     "height":"10",
     "location":"park"
  },
  "bikes":{
     "name":"c",
     "age":"110",
     "height":"10",
     "location":"park"
  }
};
const selected = Object.values(obj).find(e => e.name === 'c');

Or try like this:

function findByName(obj, name) {
  const selected = Object.entries(tmp).find(([_, e]) => e.name === 'c');
  const [key, findObj] = selected;
    return {
      [key]: findObj
    }
}
console.log(findByName(tmp, 'c'));
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement