Reputation: 146
I want to change one item from array from app locals variable and i am not sure how to do this
Here is what i have set as global
app.locals.products=[{name: 'a',url: '/a' },
{name: 'b',url: '/b' },
{name: 'c',url: '/c' },...
I want to edit them and set active product from routes and do something like this
products:[{name: 'a',url: '/a' active:true}],
But when i do this it will remove all the other items and set only the product the one i wrote. Is there a way to edit just the one i need and leave all the rest unchanged?
Upvotes: 1
Views: 659
Reputation: 2314
You can use the array find function to find a specific item in the products array and edit it.
function setActive(name) {
var element = products.find(function(product) {
return product.name === name;
});
if (element) {
element.active = true;
}
}
This function takes the name
variable, checks if it exists in the product
array and sets it to active. You might want to throw an exception if it doesn't.
Usage:
setActive('a');
Upvotes: 2