Hosen
Hosen

Reputation: 139

react facing issues to find out specific data from an array of objects

I have a few collections of data that are in JSON format and want to access specific data conditional data, an example I want to access which one has teacher:true and put it in a state. I have tried it with conditions inside the loop and filter function.

[
  0:{name:"Rou",id:"121"}
  1:{name:"Sou",id:"122",teacher:"true"}
  2:{name:"Tou",id:"123"}
  3:{name:"Vou",id:"124",teacher:"true"}
  4:{name:"Kou",id:"125",teacher:"false"}
  5:{name:"Wou",id:"126"}
]

here I want to get only

 1:{name:"Sou",id:"122",teacher:"true"}
 3:{name:"Vou",id:"124",teacher:"true"}

which means only where the teacher is true.

Upvotes: 0

Views: 25

Answers (1)

Ahmed Shaqanbi
Ahmed Shaqanbi

Reputation: 783

This has nothing to do with react. It's a javascript array problem.

let people = [
  {name:"Rou",id:"121"},
  {name:"Sou",id:"122",teacher:"true"},
  {name:"Tou",id:"123"},
  {name:"Vou",id:"124",teacher:"true"},
  {name:"Kou",id:"125",teacher:"false"},
  {name:"Wou",id:"126"}
];

let teachers = people.filter((person) => person.teacher == "true");

Note that you need it's strongly recommended to use a boolean type instead of a string:

// Strongly discouraged
{name:"Sou",id:"122",teacher:"true"};

// Better
{name:"Sou",id:"122",teacher: true};

Upvotes: 1

Related Questions