我正在尝试通过传递我想要分组的键来分组对象数组 作为我写的函数的参数,例如,如果我有3个对象的数组:
[{date: "2018-01-01", website: "example.com", revenue: 100},
{date: "2018-01-01", website: "example2.com", revenue:200},
{date: "2018-01-02", website: "example.com", revenue: 300}]
我将把它们传递给我的函数:
groupArr(arr, prop) {
return arr.reduce(function (groups, item) {
const val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups
}, {})
}
结果将是:{2018-01-01: Array(2), 2018-01-02: Array(1)}
但现在我想弄清楚如何更改此功能,我可以传递两个参数,例如日期和网站:groupArr(arr,["date","website"]
所以我的结果将包括两个参数组,在我的情况下最终会像这样:
{{[2018-01-01,"example.com"]: Array(1),[2018-01-01,"example2.com"]: Array(1), 2018-01-02: Array(1)}
为了方便起见,我将结果键呈现为数组,不确定这是否是正确的方法。 任何想法我怎么能实现这一目标?感谢
答案 0 :(得分:1)
您可以创建一个由所需属性的值组成的新密钥。
function groupArr(arr, ...props) {
return arr.reduce(function (groups, item) {
const key = props.map(k => item[k]).join('|');
groups[key] = groups[key] || [];
groups[key].push(item);
return groups;
}, {});
}
var array = [{ date: "2018-01-01", website: "example.com", revenue: 100 }, {date: "2018-01-01", website: "example2.com", revenue: 200 }, { date: "2018-01-02", website: "example.com", revenue: 300 }, { date: "2018-01-01", website: "example.com", revenue: 340 }];
grouped = groupArr(array, "date", "website");
console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)
您可以执行以下操作:
let arr = [{date: "2018-01-01",website: "example.com",revenue: 100},{date: "2018-01-01",website: "example2.com",revenue: 200},{date: "2018-01-02",website: "example.com",revenue: 300}];
function groupArr(arr, prop) {
prop = Array.isArray(prop) ? prop : [prop]; //Make sure that prop is an array. Convert to array if not
return arr.reduce(function(groups, item) {
const val = prop.map(o => item[o]).join('-'); //Map and Concat all values of prop and use as key
groups[val] = groups[val] || [];
groups[val].push(item);
return groups
}, {})
}
//Will work if prop is array
let result = groupArr(arr, ["date", "website"]);
console.log(result);
//Will work if string
let result2 = groupArr(arr, "date");
console.log(result2);