Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating a json with nested objects and filtering depending on attributes values

I have the following kind of json file:

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

What happens in my react app is that I send this json from app.js to a child component(1) and from there I send single values to another component(2) so as to represent in a row.
Now I have a problem which is I want to send to send data in component(2) only when height!=0.0 which I am not able to do.

This is my component(1):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{Object.entries(props.data).map(
  ([key, {
    // name, age, height, location
    ...e
  }]) => {
    return (<tr> <Single key={key} {...e} /> </tr>)
  }
)}

I want to filter it such that no data is given to Single component that has height == 0.0

>Solution :

You can first get the pair of key-value using Object.entries and then filter out the values that you don’t want using filter. Simple

const result = Object.entries(obj)
                     .filter((o) => o[1].height !== "0.0")
                     .map([k, v] => (<tr> <Single key={key} {...e} /> </tr>))
const obj = {
  trees: {
    name: "a",
    age: "9",
    height: "10",
    location: "park",
  },
  cars: {
    name: "b",
    age: "3",
    height: "0.0",
    location: "park",
  },
  bikes: {
    name: "c",
    age: "110",
    height: "0.0",
    location: "park",
  },
};

const result = Object.entries(obj).filter((o) => o[1].height !== "0.0");
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading