Reputation: 1
I am trying to filter some records coming from my api data, i am trying to use filter but i am not sure how should i do for multipoe items.
Here is my code the api response i have and what happens when i do a checkbox
my APi data
{
"requestId": "",
"totalRecords": 132,
"status": "SUCCESS",
"items": [
{
"Id": 3489,
"Status":"Awaiting Funds",
"amountPaid": {
"unit": "CAD",
"value": 10
},
"Name": "John Doe"
},
{
"Id": 3508
"Status":"Awaiting Funds",
"amountPaid": {
"unit": "CAD",
"value": 10
},
"Name": "John Doe"
},
{
"Id": 3503,
"Status":"Awaiting Funds",
"amountPaid": {
"unit": "CAD",
"value": 25
},
"Name": "John Sinth"
}
]
}
and in my checkbnox i am passing two checkboxes values which are full object like 3508,3503 but now sure how to do
Here is my code as to what i did but i am not getting filetered records
const parsedData = JSON.parse(JSON.stringify(this.apiData));
if (this.multipleSelection.length > 0) {
const data = parsedData.filter(function (el)
{
return el.Id = 3489 and 3503
})
} else {
const data = parsedData;
}
Upvotes: 0
Views: 49
Reputation: 206048
Use Array.prototype.filter() in combination with Array.prototype.includes()
const data = {
"requestId": "",
"totalRecords": 132,
"status": "SUCCESS",
"items": [
{
"Id": 3489,
"Status":"Awaiting Funds",
"amountPaid": {"unit": "CAD","value": 10},
"Name": "John Doe"
},{
"Id": 3508,
"Status":"Awaiting Funds",
"amountPaid": {"unit": "CAD","value": 10},
"Name": "John Doe"
},{
"Id": 3503,
"Status":"Awaiting Funds",
"amountPaid": {"unit": "CAD","value": 25},
"Name": "John Sinth"
}
]
};
const ids = [3503, 3508];
const parsedData = data.items.filter((item) => ids.includes(item.Id));
console.log(parsedData)
if the above is still not clear, here's an example that uses checkboxes:
const data = {
"requestId": "",
"totalRecords": 132,
"status": "SUCCESS",
"items": [
{
"Id": 111,
"Status":"Awaiting Funds",
"amountPaid": {"unit": "CAD","value": 10},
"Name": "John Doe"
},{
"Id": 222,
"Status":"Awaiting Funds",
"amountPaid": {"unit": "CAD","value": 10},
"Name": "John Doe"
},{
"Id": 333,
"Status":"Awaiting Funds",
"amountPaid": {"unit": "CAD","value": 25},
"Name": "John Sinth"
}
]
};
const filterByIds = (ids) => data.items.filter((item) => ids.includes(+item.Id));
const elsIdInputs = document.querySelectorAll("[name='id']");
elsIdInputs.forEach((elId) => {
elId.addEventListener("input", () => {
const ids = [...elsIdInputs].filter(el => el.checked).map(el => +el.value);
console.log(ids)
if (!ids.length) return; // Exit. (none is checked)
// Else... do something here
console.clear();
console.log(filterByIds(ids));
});
});
<label><input type="checkbox" name="id" value="111"> 111</label>
<label><input type="checkbox" name="id" value="222"> 222</label>
<label><input type="checkbox" name="id" value="333"> 333</label>
Upvotes: 1