Javascript 按公共属性将嵌套数组中的对象分组到小计数组中

Javascript 按公共属性将嵌套数组中的对象分组到小计数组中,javascript,arrays,object,lodash,Javascript,Arrays,Object,Lodash,我有个问题找不到解决的办法。 我有一组按属性分组的数组: [ [ {Id:'211321',发件人:'Customer 1',价格:120,金额:2}, {Id:'211341',发件人:'Customer 1',价格:320,金额:5}, {Id:'212351',发件人:'Customer 1',价格:300,金额:2}, {Id:'234121',发件人:'Customer 1',价格:230,金额:3}, {Id:'223321',发件人:'Customer 1',价格:410,金额:

我有个问题找不到解决的办法。 我有一组按属性分组的数组:

[
[
{Id:'211321',发件人:'Customer 1',价格:120,金额:2},
{Id:'211341',发件人:'Customer 1',价格:320,金额:5},
{Id:'212351',发件人:'Customer 1',价格:300,金额:2},
{Id:'234121',发件人:'Customer 1',价格:230,金额:3},
{Id:'223321',发件人:'Customer 1',价格:410,金额:1}
],
[
{Id:'2321',发件人:'Customer 2',价格:120,金额:2},
{Id:'21341',发件人:'Customer 2',价格:320,金额:5},
{Id:'2351',发件人:'Customer 2',价格:300,金额:2},
{Id:'4121',发件人:'Customer 2',价格:230,金额:3},
{Id:'3321',发件人:'Customer 2',价格:410,金额:1}
],
[
{Id:'3453',发件人:'Customer 3',价格:520,金额:2},
{Id:'4334',发件人:'Customer 3',价格:220,金额:5},
{Id:'2343',SendFrom:'Customer 3',价格:700,金额:2},
{Id:'6654',发件人:'Customer 3',价格:430,金额:3},
{Id:'4534',发件人:'Customer 3',价格:210,金额:1}
]

]
您可以对对象进行分组,并将所有需要的值添加到其属性中。最后,仅从对象中获取值

var data=[{Id:'211321',发送发件人:'Customer 1',价格:120,金额:2},{Id:'211341',发送发件人:'Customer 1',价格:320,金额:5},{Id:'212351',发送发件人:'Customer 1',价格:300,金额:2},{Id:'Customer 1',价格:230,金额:3},{Id:'223321',发送发件人:'Customer 1',价格:410,金额:1}[{Id:'2321',发件人:'Customer 2',价格:120,金额:2},{Id:'21341',发件人:'Customer 2',价格:320,金额:5},{Id:'2351',发件人:'Customer 2',价格:300,金额:2},{Id:'4121',发件人:'Customer 2',价格:230,金额:3},{Id:'3321',发件人:'Customer 2',价格:410,金额:1}[{Id:'3453',发件人:'Customer 3',价格:520,金额:2},{Id:'4334',发件人:'Customer 3',价格:220,金额:5},{Id:'2343',发件人:'Customer 3',价格:700,金额:2},{Id:'6654',发件人:'Customer 3',价格:430,金额:3},{Id:'4534',发件人:'Customer 3',价格:210,金额:1}],
grouped=Object.values(data.flat().reduce)(r,{SendFrom,Price,Amount})=>{
r[SendFrom]=r[SendFrom]|{SendFrom,价格:0,金额:0};
r[SendFrom]。价格+=价格;
r[SendFrom]。金额+=金额;
返回r;
}, {}));
console.log(分组);

。作为控制台包装{max height:100%!important;top:0;}
您的输入看起来不正确。它既不是数组也不是对象。而且您没有指定“如何”你想要更新输出。它总是一组中所有的价格和金额的总和吗?嗨,Rahul,是的,它总是一组中所有的价格和金额的总和。关于输入,我几乎可以肯定它是一个对象数组,但我可能错了。下面是Checkout@Nina Scholz solution。它很好,似乎也修复了输入。Thanks,这是我所需要的。谢谢@Yevgen的解释。我将保存它来研究它,它工作很好,如果我了解它是如何工作的就更好了works@AmericoPerez:感谢您的回复,希望您已经复制了您需要的内容,因为我已经删除了我的答案。建议您解释一下您的代码如何解决OP的任务ion。只有代码的答案是不受欢迎的。添加信息可以让访问者快速放大重要部分,更快地进行认知消化,帮助fire访问者学习,并将知识应用到他们自己的代码中。这有利于知识问答,而不是“给我代码”作为服务Q和A,它也保持质量高,所以作为一个平台。考虑添加一些解释到您的答案。
var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

console.log(groupBy(['one', 'two', 'three'], 'length'));

// => {3: ["one", "two"], 5: ["three"]}
var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

console.log(groupBy(your_array_name, 'SendFrom'));