-3

I have an object with name-value pairs. How can I target and remove specific name-value pair if all I have is the value?

{
  1: 'foo',
  2: 'boo',
  3: 'goo',
  4: 'moo'
}

Please note this is important - all i have is 'boo', and possibility is that this value will change the number in the future. I need to target the exact string.

Kutyel
  • 8,575
  • 3
  • 30
  • 61

5 Answers5

1

Since the question was tagged with lodash, then you might want to use its omitBy function, that removes a certain property of an object based on the return value of its predicate callback function.

const result = _.omitBy(object, v => v === 'foo');

const object = {
  1: 'foo',
  2: 'boo',
  3: 'goo',
  4: 'moo'
};

const result = _.omitBy(object, v => v === 'foo');

console.log(result);
.as-console-wrapper{min-height:100%;top:0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
ryeballar
  • 29,658
  • 10
  • 65
  • 74
0

Functional, immutable solution:

const cleanObj = (obj, val) => 
  Object.entries(obj)
    .filter(([key, value]) => value !== val)
    .reduce((o, [k, v]) => ({ ...o, [k]: v }), {})
Kutyel
  • 8,575
  • 3
  • 30
  • 61
0

Using this answer and a for.

If you want to delete multiple properties with that value, remove the return obj; from inside the for.

var valueToRemove = 'boo';
var myObj = {
  1: 'foo',
  2: 'boo',
  3: 'goo',
  4: 'moo'
};

console.log(myObj);
removePropertyByValue(myObj, valueToRemove)
console.log(myObj);

function removePropertyByValue(obj, value) {
  for(var prop in obj) {
    if(obj[prop] == value) {
      delete obj[prop];
      return obj;
    }
  }
  return obj;
}
raul.vila
  • 1,984
  • 1
  • 11
  • 24
0

Actually I've made it a bit simpler:

const newObj = map(myObj, value => value !== valueToRemove)

So there you go.

Kutyel
  • 8,575
  • 3
  • 30
  • 61
0

You can use for...of to iterate the entries of the object, and build a new object from the entries that don't have the specified value:

const obj = {
  1: 'foo',
  2: 'boo',
  3: 'goo',
  4: 'moo'
}

const omitKeyByValue = (val) => {
  const r = {};
  
  for(const [k, v] of Object.entries(obj)) {
    if(obj[k] !== val) r[k] = v;
  }

  return r;
};


console.log(omitKeyByValue('boo'));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209