[英]How to remove unmatched objects from array of objects using javascript or lodash
[英]JavaScript/lodash: How to remove objects from object by value with omitBy?
我有一个 object:
const obj = {
1: { "id": 1, "taskId": 1, },
2: { "id": 2, "taskId": 2, },
3: { "id": 3, "taskId": 2, },
4: { "id": 4, "taskId": 3, },
};
我需要使用键“taskId”删除所有对象: 2. 不知道如何编写 fn 以与 omitBy 一起使用。 任何人都可以帮忙吗?
console.log(_.omitBy(obj, ???));
是否有可能与来自lodash的“omitBy”function有关? 还是我需要另辟蹊径?
在回调中,只需从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>
在不依赖库的情况下完成是微不足道的,但是,不需要 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) ) );
您可以使用_.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.