使用 lodash 通过两个键获取对象组数组
Get a array of object group by two keys using loadash
输入:
[
{
"Country": "BR",
"New Lv1-Lv2": "#N/A"
},
{
"Country": "BR",
"New Lv1-Lv2": "#N/A"
},
{
"Country": "",
"New Lv1-Lv2": "test"
}]
输出:
[
{
"Country": "BR",
"New Lv1-Lv2": "#N/A",
"count":2
},
{
"Country": "",
"New Lv1-Lv2": "test",
"count":1
}]
我使用了 loadhash group by 但不确定如何映射多个键请告诉我如何完成
构建一个具有聚合计数的对象。
(PS.根据自己的需要修改key,要唯一)
const convert = (arr) => {
const res = {};
arr.forEach((obj) => {
const key = `${obj.Country}${obj["New Lv1-Lv2"]}`;
if (!res[key]) {
res[key] = { ...obj, count: 0 };
}
res[key].count += 1;
});
return Object.values(res);
};
const data = [
{
Country: "BR",
"New Lv1-Lv2": "#N/A",
},
{
Country: "BR",
"New Lv1-Lv2": "#N/A",
},
{
Country: "",
"New Lv1-Lv2": "test",
},
];
console.log(convert(data));
输入:
[
{
"Country": "BR",
"New Lv1-Lv2": "#N/A"
},
{
"Country": "BR",
"New Lv1-Lv2": "#N/A"
},
{
"Country": "",
"New Lv1-Lv2": "test"
}]
输出:
[
{
"Country": "BR",
"New Lv1-Lv2": "#N/A",
"count":2
},
{
"Country": "",
"New Lv1-Lv2": "test",
"count":1
}]
我使用了 loadhash group by 但不确定如何映射多个键请告诉我如何完成
构建一个具有聚合计数的对象。 (PS.根据自己的需要修改key,要唯一)
const convert = (arr) => {
const res = {};
arr.forEach((obj) => {
const key = `${obj.Country}${obj["New Lv1-Lv2"]}`;
if (!res[key]) {
res[key] = { ...obj, count: 0 };
}
res[key].count += 1;
});
return Object.values(res);
};
const data = [
{
Country: "BR",
"New Lv1-Lv2": "#N/A",
},
{
Country: "BR",
"New Lv1-Lv2": "#N/A",
},
{
Country: "",
"New Lv1-Lv2": "test",
},
];
console.log(convert(data));