简体   繁体   中英

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?

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM