1

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.