Will Black
Will Black

Reputation: 402

JavaScript/lodash: How to remove objects from object by value with omitBy?

I have an object:

const obj = { 
  1: { "id": 1, "taskId": 1, },
  2: { "id": 2, "taskId": 2, },
  3: { "id": 3, "taskId": 2, },
  4: { "id": 4, "taskId": 3, },
};

I need to remove all objects with keys 'taskId': 2. Have no idea how to write fn to use with omitBy. Can anyone help?

console.log(_.omitBy(obj, ???));

is it possible to do with "omitBy" function from lodash? or I need to find another way?

Upvotes: 1

Views: 4019

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

You can use _.omitBy() and pass an object with the properties and values you want to remove:

const obj = { 
  1: { "id": 1, "taskId": 1, },
  2: { "id": 2, "taskId": 2, },
  3: { "id": 3, "taskId": 2, },
  4: { "id": 4, "taskId": 3, },
};

const result = _.omitBy(obj, { taskId: 2 });

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370789

In the callback, just take the taskId property from the object, and check if it's 2:

const obj = { 
  1: { "id": 1, "taskId": 1, },
  2: { "id": 2, "taskId": 2, },
  3: { "id": 3, "taskId": 2, },
  4: { "id": 4, "taskId": 3, },
};

console.log(
  _.omitBy(
    obj,
    ({ taskId }) => taskId === 2
  )
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

It's trivial to accomplish without relying on a library, though, no need for Lodash:

const obj = { 
  1: { "id": 1, "taskId": 1, },
  2: { "id": 2, "taskId": 2, },
  3: { "id": 3, "taskId": 2, },
  4: { "id": 4, "taskId": 3, },
};

console.log(
  Object.fromEntries(
    Object.entries(obj)
      .filter(([, { taskId }]) => taskId !== 2)
  )
);

Upvotes: 3

Related Questions