I have a problem with creating code. First, here is a categories array with field property. The second array is an element of categories with a property field (this property is the same as in category so I can recognize which element suits to category). How I can add property "edit" and "browse" to "categories" basing on elements of categories? It's something like a global checkbox if all of the elements with a category for example "tags" have edit or browse true/false then add a property to this category.
const categories = [
{
name: "Tags",
field: "tags",
//Here and in every object I want to add property edit: true/false, browse: true/false if all categoriesElements with field "tags" or other are true.
hideFinance: false
},
{
name: "Pixels",
field: "retargeting_pixels",
hideFinance: false
},
{
name: "Dashboard",
field: "dashboard",
hideFinance: false
}
];
const categoriesElements = [
{
name: "Tags finance",
field: "tags",
edit: true,
browse true
},
{
name: "Tags channels",
field: "tags",
edit: true,
browse true
},
{
name: "Pixel creators",
field: "pixel",
edit: true,
browse true
}
]
You can use map
and filter
to achieve this. Below is the example of how you use the map an array based on other array.
const categories = [
{
name: "Tags",
field: "tags",
hideFinance: false
},
{
name: "Pixels",
field: "retargeting_pixels",
hideFinance: false
},
{
name: "Dashboard",
field: "dashboard",
hideFinance: false
}
];
const categoriesElements = [
{
name: "Tags finance",
field: "tags",
edit: true,
browse: true
},
{
name: "Tags channels",
field: "tags",
edit: true,
browse: true
},
{
name: "Pixel creators",
field: "pixel",
edit: true,
browse: true
}
]
categories.map(cat=> {
const ce = categoriesElements.filter(el=> el.field == cat.field);
cat.edit = ce.length > 0 ? ce.every(elm => elm.edit) : false;
cat.browse = ce.length > 0 ? ce.every(elm => elm.browse) : false;
return cat;
})
console.log('categories', categories)