Joe Isaacson
Joe Isaacson

Reputation: 4132

How do I omit a key pair from an object based on its value?

I am using lodash.js and am trying to remove a key pair from the below object based on the value not the key name - note, I cannot use the key name:

var filters = {
   "filter1": "height",
   "filter2": "length",
   "filter3": "width"
}

This will remove a key pair by name

_.omit(filters, 'filter1');

Does anyone know how to removed it based upon value? Cheers

Upvotes: 2

Views: 802

Answers (4)

NiRUS
NiRUS

Reputation: 4259

Answer updated (2023) : v4.17.15

API : omitBy(object, predicate)

[predicate=_.identity] (Function): The function invoked per property.

use omitBy that accepts a function callback on each value to be processed.

_.omitBy(filters, function (value) {
    return value === 'width';
})

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187034

According to the docs omit it can take a call back argument that is a function that returns true for each pair that should be omitted. In that function you can do whatever crazy logic you like.

_.omit(filters, function(value, key, object) {
  return value === 'width'; // omit width
});

Upvotes: 2

p.s.w.g
p.s.w.g

Reputation: 149020

The omit method accepts a callback, so you could just use this:

_.omit(filters, function(v){return v == "height";});

Demonstration

Upvotes: 2

Ry-
Ry-

Reputation: 224942

You can use _.omit with a callback:

_.omit(filters, function (value) {
    return value === 'width';
})

Upvotes: 3

Related Questions