I have this object:
const data =
{
"avaiable_items": {"1": [201259, 201303],"2": [201303], "3": [201259]},
"items": [{"id": "201259","name": "ABC"},{"id": "201303","name": "DEF"}]
}
I need to filter "items"
based on "avaiable_items"
dynamic keys
Example if want to filter object based on selected avaiable_items
i.e "1"
, the result will be:
{
"item": [{"id": "201259","name": "ABC"},{"id": "201303","name"}]
}
CodePudding user response:
Does this do what you want?
const keys = new Set(data.avaiable_items['1']);
data.items.filter(({id}) => keys.has(Number(id)));
CodePudding user response:
Apologies if I have misunderstood, however this should work:
const data =
{
"avaiable_items": {"1": [201259, 201303],"2": [201303], "3": [201259]},
"items": [{"id": "201259","name": "ABC"},{"id": "201303","name": "DEF"}]
}
let filterOn = "1";
const newData = data.items.filter(key => {
return data['avaiable_items'][filterOn].includes(parseInt(key.id));
});
console.log(newData);
The above will just filter (and return) those in items[]
which contain an id
found in avaiable_items[x]
.
CodePudding user response:
A simple vanilla answer would do:
const myFilter = (
target = '',
{available_items = [], items = [], stock = available_items [target] ?? []} = {}
) => items .filter (({id}) => stock. includes (Number (id)))
const data = {available_items: {1: [201259, 201303], 2: [201303], 3: [201259]}, items: [{id: "201259", name: "ABC"}, {id: "201303", name: "DEF"}]}
console .log ('1:', myFilter (1, data))
console .log ('2:', myFilter (2, data))
console .log ('3:', myFilter (3, data))
console .log ('4:', myFilter (4, data))
.as-console-wrapper {max-height: 100% !important; top: 0}
Although we could certainly use Ramda's filter
and includes
in place of the native ones, and could extend this to some point-free version if we tried hard enough, I don't see that it would improve the code at all in this case.