I have these objects
const data = [
{
id: 1,
recipient: "001",
assessment: "Apta",
score: "2",
ovarian: "E1",
},
{
id: 2,
recipient: "ABC2",
assessment: "Apta",
score: "2,5",
ovarian: "E1",
},
{
id: 3,
recipient: "003",
assessment: "Refugo",
score: "3",
ovarian: "E1",
},
{
id: 4,
recipient: "004",
assessment: "Apta",
score: "4",
ovarian: "E2",
},
];
And this is my code, which when it finds the correct string it returns me:
const searchAnimal = value => {
setInput(value);
JSON.parse(records).filter(item => {
if (item.recipient === value) {
setSearch([item]);
}
});
};
What would the logic be to return all object.recipients that start with 00? Would a regex maybe do it?
CodePudding user response:
I think changing a little bit the logic would help:
let search = function (data, searchString) {
return data.filter((item) => {
return item.recipient.includes(searchString);
});
};
By doing so will give you the object you're searching for.
CodePudding user response:
You can filter for the objects with a recipient that starts with 00 by using:
const array00Animals = data.filter((animal) => animal.recipient.substr(0, 2) === '00');
This will return the array of objects but only id's 1, 3 and 4 from your sample data.