I need to filter role from children of array based on other array, but i'm still confused on using filter in my case
this is the base array :
arr1 = [
{
name: 'test1',
children: [
{
name: 'one',
role: 'menu_one'
},
{
name: 'two',
role: 'menu_two'
},
{
name: 'three',
role: 'menu_three'
}
]
},
{
name: 'test2',
children: [
{
name: 'four',
role: 'menu_four'
},
{
name: 'five',
role: 'menu_five'
}
]
}
]
this is accepted role :
arr2 = ['menu_one', 'menu_three', 'menu_four']
this is what i'am trying to accomplish:
arr1 = [
{
name: 'test1',
children: [
{
name: 'one',
role: 'menu_one'
},
{
name: 'three',
role: 'menu_three'
}
]
},
{
name: 'test2',
children: [
{
name: 'four',
role: 'menu_four'
}
]
}
]
I try this and is not work, did i use it wrong?
var result = arr1.filter(function(item) {
return arr2.includes(item.children.role);
})
I hope someone can help my case
CodePudding user response:
You could use Array.map()
, along with Array.filter()
to get the required result.
In each iteration, we'd filter the children of each item, by checking that their role is present in the arr2 array.
arr1 = [ { name: 'test1', children: [ { name: 'one', role: 'menu_one' }, { name: 'two', role: 'menu_two' }, { name: 'three', role: 'menu_three' } ] }, { name: 'test2', children: [ { name: 'four', role: 'menu_four' }, { name: 'five', role: 'menu_five' } ] }, { name: 'test3 - no children' } ]
arr2 = ['menu_one', 'menu_three', 'menu_four'];
const result = arr1.map(({ name, children }) => {
return {
name,
children: children ? children.filter(child => arr2.includes(child.role)) : null
};
})
console.log('Result:', result)
You could also improve efficiency (if arr2 is big!) by creating a Set
to check if the role is present in the item.
arr1 = [ { name: 'test1', children: [ { name: 'one', role: 'menu_one' }, { name: 'two', role: 'menu_two' }, { name: 'three', role: 'menu_three' } ] }, { name: 'test2', children: [ { name: 'four', role: 'menu_four' }, { name: 'five', role: 'menu_five' } ] }, { name: 'test3 - no children' } ]
arr2 = ['menu_one', 'menu_three', 'menu_four'];
let roleSet = new Set(arr2);
const result = arr1.map(({ name, children }) => {
return {
name,
children: children ? children.filter(child => roleSet.has(child.role)) : null
};
})
console.log('Result:', result)