如何对对象数组进行分组并转换重复项
大家好,我有这个数据结构,我需要对其进行分组,如果有任何重复项可以将这两个对象转换为一行。.
数据结构
var shipTo = [
{ addressLine1: "address 1", name: "Jeff" },
{ addressLine1: "address 2", name: "Taylor" },
{ addressLine1: "address 1", name: "Megan" },
{ addressLine1: "address 3", name: "Madison" },
];
分组函数
function groupArrayOfObjects(list, key) {
return list.reduce(function (rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
}
我有groupedBy 地址 attrube 通过上面这个函数的地址
const groupedAddress = groupArrayOfObjects(shipTo, "addressLine1");
我的新数据结构是
我的最终结果希望是这样的:
货件 1 和 1 的送货地址3 是“地址 1”
货件 2 的送货地址是“地址 2”
Hello to all i have this data structure that i need to group and if there are any duplicates to convert those two objects it in one line..
Data Structure
var shipTo = [
{ addressLine1: "address 1", name: "Jeff" },
{ addressLine1: "address 2", name: "Taylor" },
{ addressLine1: "address 1", name: "Megan" },
{ addressLine1: "address 3", name: "Madison" },
];
Grouped function
function groupArrayOfObjects(list, key) {
return list.reduce(function (rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
}
I have groupedBy address attrube by this function above by address
const groupedAddress = groupArrayOfObjects(shipTo, "addressLine1");
My new data-structure is
My final Result wanna be like this :
Shipping Address for Shipment 1 & 3 is "address 1"
Shipping Address for Shipment 2 is "address 2"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
reduce
可以将当前数组元素的索引作为第三个参数。然后你可以将它传递给你的累加器,并在最终的数组中可以用它做你想做的事情reduce
can take the index of the current array element as the 3rd parameter. you can then pass it to your accumulator and in the final array can do what you want with it