how can I remove a specific value from a property in an object (not the entire property)? In the code below I want to remove for example the value "larry from property "names" from object items. Thank you
const items = {
names: ["mike", "larry"],
cities: ["2London"]
}
const remove = (items, category, el) => {
return Object.keys(items).filter(item => {
return item[category] !== el
})
}
2 using spead operator (removes entire property):
let {[category]: el, ...result} = items
remove(items, "names", "larry")
Do you want to modify in-place or return a copy? If you want a copy, you can return a spread object with the filtered category.
const items = {
names: ['mike', 'larry'],
cities: ['2London']
};
const remove = (items, category, el) => ({
...items,
[category]: items[category].filter(e => e !== el)
});
const modified = remove(items, 'names', 'larry');
console.log(modified);
For modifying in-place, you can try the following:
const items = {
names: ['mike', 'larry'],
cities: ['2London']
};
const remove = (items, category, el) => {
const arr = items[category];
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] === el) {
arr.splice(i, 1);
}
}
return items; // can be assigned (optional)
};
remove(items, 'names', 'larry'); // modified
console.log(items);
Here is a greedy version of the remove
function from above:
const items = {
names: ['mike', 'larry'],
cities: ['2London']
};
const remove = (items, category, el) => {
const arr = items[category];
for (let i = 0; i < arr.length; i++) {
if (arr[i] === el) {
arr.splice(i, 1);
break;
}
}
return items;
};
remove(items, 'names', 'larry'); // modified
console.log(items);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments