0

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")

4 Answers 4

2

you can try this

const items = {
  names: ["mike", "larry"],
  cities: ["2London"]
}

const remove = (items, category, el) => {
  items[category] = items[category].filter(item => {
    return item !== el;
  });
}

remove(items, "names", "larry");
console.log(items);

1

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);

2
  • you for loop won't break till traverse whole. Commented Jan 27, 2021 at 4:53
  • @cybercoder that’s because I wanted to remove all instances of that item. I’ll add a greedy version. Commented Jan 27, 2021 at 12:20
0

var items = {
  names: ["mike", "larry", "eva", "john"],
  cities: ["2London"]
};

const remove= (obj,key,value)=>{
    let index = (obj[key]).findIndex(i=>i===value);
    return index !== -1 ? obj[key].splice(index,1):0
}

remove(items,'names','eva');

console.log(items);

0

In case you're interested in avoiding the helper function for a one-off removal, consider:

const items = {
  names: ["mike", "larry"],
  cities: ["2London"]
}    

items.names = items.names.filter(name => name !== "larry");

console.log(items);