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

Time:12-18

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):

{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

CodePudding user response:

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);

  • Related