gpt4 book ai didi

javascript - 使用 lodash 过滤缺失的数组对象

转载 作者:行者123 更新时间:2023-12-03 03:57:19 24 4
gpt4 key购买 nike

在我的 Angular 4 应用程序中,我有以下数组:

let sampleArray1 = [
{
"name":"Raman",
"prdList":[
{
"p_code":"20",
"crtList":[
{
"c_code":"087"
}
]
}
]
},
{
"name":"Laxman",
"prdList":[
{
"p_code":"10"
}
]
},
{
"name":"raj",
"prdList":[
{
"p_code":"202"
}
]
},
{
"name":"raghav",
"prdList":[
{
"p_code":"30",
"crtList":[
{
"c_code":"97"
}
]
}
]
}
]

在此数组中,某些对象缺少 crtList。我需要过滤掉所有此类对象,并且需要拥有必须且应该具有 crtList 的数组。

所以我的结果sampleArray2应该有以下结果:

 [
{
"name":"Raman",
"prdList":[
{
"p_code":"20",
"crtList":[
{
"c_code":"087"
}
]
}
]
},
{
"name":"raghav",
"prdList":[
{
"p_code":"30",
"crtList":[
{
"c_code":"97"
}
]
}
]

} ]

如何使用 lodash 实现此目的?

最佳答案

实际上,要获取sampleArray2,您不需要lodash。一个简单的 Array.prototype.filter 就足够了:

let sampleArray1 = [
{
"name":"Raman",
"prdList":[
{
"p_code":"20",
"crtList":[
{
"c_code":"087"
}
]
}
]
},
{
"name":"Laxman",
"prdList":[
{
"p_code":"10"
}
]
},
{
"name":"raj",
"prdList":[
{
"p_code":"202"
}
]
},
{
"name":"raghav",
"prdList":[
{
"p_code":"30",
"crtList":[
{
"c_code":"97"
}
]
}
]
}
];

let result = sampleArray1.filter(function(x) {
return hasCrtList(x.prdList);
});

function hasCrtList(prdList) {
for (var i in prdList) {
if (prdList[i].crtList) {
return true;
}
}
return false;
}

console.log(result);

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

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