gpt4 book ai didi

javascript - 使用 lodash 根据条件过滤对象数组中的数据

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:42 25 4
gpt4 key购买 nike

我有下面的对象集数组,我需要使用 lodash 根据条件从整个数组集中获取其中的一些对象。

我在lodash中使用了_.filter(data, condition),但预期结果不是 future 。

有人帮我解决这个问题吗?

条件:EarnCode < 90 && 小时 === 0(结果将跳过这些数据)。

请求数组集:

[
{
"id" : 1,
"EmpId" : 100,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "20180213.2015-06.2768.6",
"EarnCode" : 96,
"Hours" : 0
},
{
"id" : 3,
"EmpId" : 100,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "20180213.2015-06.2768.6",
"EarnCode" : 96,
"Hours" : 0
},
{
"id" : 2,
"EmpId" : 100,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "20180213.2015-06.2768.6",
"EarnCode" : 1,
"Hours" : 0
},
{
"id" : 5,
"EmpId" : 100,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "20180213.2015-06.2768.6",
"EarnCode" : 1,
"Hours" : 3
}
]

预期结果:

[
{
"id" : 1,
"EmpId" : 100,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "20180213.2015-06.2768.6",
"EarnCode" : 96,
"Hours" : 0
},
{
"id" : 3,
"EmpId" : 100,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "20180213.2015-06.2768.6",
"EarnCode" : 96,
"Hours" : 0
},
{
"id" : 5,
"EmpId" : 100,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "20180213.2015-06.2768.6",
"EarnCode" : 1,
"Hours" : 3
}
]

最佳答案

为了完整起见,如果您坚持必须使用 lodash,请遵循 CRice 的答案,这可能是解决此问题的方法:

const inputSet = [{
"id": 1,
"EmpId": 100,
"AcctCode": "2001-00",
"SuperID": 2000,
"ReportNo": "20180213.2015-06.2768.6",
"EarnCode": 96,
"Hours": 0
}, {
"id": 3,
"EmpId": 100,
"AcctCode": "2001-00",
"SuperID": 2000,
"ReportNo": "20180213.2015-06.2768.6",
"EarnCode": 96,
"Hours": 0
}, {
"id": 2,
"EmpId": 100,
"AcctCode": "2001-00",
"SuperID": 2000,
"ReportNo": "20180213.2015-06.2768.6",
"EarnCode": 1,
"Hours": 0
}, {
"id": 5,
"EmpId": 100,
"AcctCode": "2001-00",
"SuperID": 2000,
"ReportNo": "20180213.2015-06.2768.6",
"EarnCode": 1,
"Hours": 3
}]

// Negate your condition, filter keeps items where the condition is
// true, so for your example, you need either Hours to be non-zero
// OR for EarnCode to be greater than 90.
const resultSet = _.filter(inputSet, i => i.Hours !== 0 || i.EarnCode >= 90);
console.log(resultSet); // Includes items 1, 3, and 5.
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

关于javascript - 使用 lodash 根据条件过滤对象数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49035440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com