I have an array of objects to be filtered:
[
{
"name": "Apple",
"age": 24,
"model": "Android",
"status": "Under development",
},
{
"name": "Roboto",
"age": 24,
"model": "Apple",
"status": "Running",
},
.
.
.
.
]
I need to filter the array using multiple parameters using JavaScript's filter
method.
I have got a partial solution but could not get the expected output.
The filter should also work with multiple values for a single attribute.
E.g., age=54,23
or model="Android","Apple"
etc.
I'm trying to mimic the working of filters just like that of an e-merce site, where we can pare all of a product’s attributes and customer’s chosen tags to output a filtered list of products.
I have an array of objects to be filtered:
[
{
"name": "Apple",
"age": 24,
"model": "Android",
"status": "Under development",
},
{
"name": "Roboto",
"age": 24,
"model": "Apple",
"status": "Running",
},
.
.
.
.
]
I need to filter the array using multiple parameters using JavaScript's filter
method.
I have got a partial solution but could not get the expected output.
The filter should also work with multiple values for a single attribute.
E.g., age=54,23
or model="Android","Apple"
etc.
I'm trying to mimic the working of filters just like that of an e-merce site, where we can pare all of a product’s attributes and customer’s chosen tags to output a filtered list of products.
Share Improve this question edited Jan 28, 2022 at 12:21 VLAZ 29.2k9 gold badges63 silver badges84 bronze badges asked Aug 21, 2020 at 10:36 Anandhan SreekumarAnandhan Sreekumar 511 silver badge6 bronze badges 2- 2 If you can post your partial solution as well, it will be easier for others to help you improve it. – Udith Gunaratna Commented Aug 21, 2020 at 10:41
- 1 Try looking here: stackoverflow./questions/31831651/… and here: gist.github./jherax/f11d669ba286f21b7a2dcff69621eb72 – Magiczne Commented Aug 21, 2020 at 10:41
1 Answer
Reset to default 6If you format your filter conditions just like an object in your data array, but with values being arrays of possible values, then you can use the filter
method as follows:
let data = [
{
"name": "Apple",
"age": 24,
"model": "Android",
"status": "Under development",
}, {
"name": "Roboto",
"age": 24,
"model": "Apple",
"status": "Running",
}, {
"name": "Samsung",
"age": 26,
"model": "Blueberry",
"status": "Running",
},
];
let filter = {
"name": ["Roboto", "Ericsson"],
"age": [22, 24, 26],
};
let res = data.filter(obj =>
Object.entries(filter).every(([prop, find]) => find.includes(obj[prop])));
console.log(res);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745222107a4617295.html
评论列表(0条)