[英]JavaScript/lodash: How to remove objects from object by value with omitBy?
I have an object:我有一个 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.我需要使用键“taskId”删除所有对象: 2. 不知道如何编写 fn 以与 omitBy 一起使用。 Can anyone help?
任何人都可以帮忙吗?
console.log(_.omitBy(obj, ???));
is it possible to do with "omitBy" function from lodash?是否有可能与来自lodash的“omitBy”function有关? or I need to find another way?
还是我需要另辟蹊径?
In the callback, just take the taskId
property from the object, and check if it's 2:在回调中,只需从
taskId
中获取 taskId 属性,并检查它是否为 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:在不依赖库的情况下完成是微不足道的,但是,不需要 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:您可以使用
_.omitBy()
并传递 object 以及要删除的属性和值:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.