gpt4 book ai didi

javascript - underscorejs groupby 和过滤器

转载 作者:行者123 更新时间:2023-12-03 06:11:50 27 4
gpt4 key购买 nike

我有一个对象数组。我想groupby & filter(remove) undefined object 、类别。为了更清楚地说明,请参阅下面的脚本:

arrayFlatten = [
{
area:"Digital",
category:undefined,
qId:"q11",
qqId:"step1",
type:"Reduce",
val:1,
userId:1,
weightedAverage:0
},
{
area:"Digital",
category:"Analytics",
qId:"q1",
qqId:"step1",
type:"Reduce",
val:1,
userId:1,
weightedAverage:0
},
{
area:"Digital",
category:"Analytics",
qId:"q1",
qqId:"step2",
type:"Reduce",
val:1,
userId:1,
weightedAverage:0
}
]

用于使用group by排序的命令

var groupCategory = _.groupBy(arrayFlatten,'category');
console.log(groupCategory);

预期结果应该如下所示:

arrayFlatten = [
{
area:"Digital",
category:"Analytics",
qId:"q1",
qqId:"step1",
type:"Reduce",
val:1,
userId:1,
weightedAverage:0
},
{
area:"Digital",
category:"Analytics",
qId:"q1",
qqId:"step2",
type:"Reduce",
val:1,
userId:1,
weightedAverage:0
}
]

最佳答案

filteredArray = _.filter(
arrayFlatten,
function (obj) {
return obj.category !== undefined;
}
);

filteredArray 将包含您的数组,没有未定义的类别。

您也可以在大多数现代浏览器中不使用下划线来执行此操作,使用此处描述的 Array.filter():https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

关于javascript - underscorejs groupby 和过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39280414/

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