0

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.

1 Answer 1

1

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};
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, thanks for your suggestion. I have another problem that is, you have solved the problem and got two users data, then how should get data from another table of those two users, or can be more users, I mean how can I fetch data from another table using these users Id.
for example, I have got two persons data which has teacher:true and id 122, 124, by using these id's and teacher:true how should get these perticular persons data from another table, example like --- let infoDetails= [{name:"Rou",id:"121", email:"[email protected]"},{name:"Sou",id:"122",teacher:"true", email:"[email protected]"},{name:"Tou",id:"123"}, {name:"Vou",id:"124",teacher:"true", email:"[email protected]"},{name:"Kou",id:"125",teacher:"false",email:"[email protected]"}]; from this table
let ids = ["122", "124"]; let teachers = people.filter((person) => person.teacher == "true" && ids.includes(person.id));
thank you, but I mean for more than two IDs or uncountable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.