我有下面的json数据。目标是获取所有订单并将它们组合为一个数组,同时保持金额和IdNumber
,以便我可以在Type上使用lodash _.groupBy
。
最后,例如,我将使用每个IdNumber和对应于该IdNumber的订单金额进行Type:测试
我在数据上尝试了Object.assign
并做了
data.forEach(d => {
let orders = d['Orders'];
let newOrders = Object.assign({}, {Idnumber: data.IdNumber, Orders: orders});
let groupedOrders = _.groupBy(newOrders, 'Type');
});
但是,我不确定如何只获取订单的数量和类型并将其合并为一个数组。我也不清楚Object.assign是否通过Orders跟踪IdNumber。通过数组时。我从未使用过Object.assign,所以也许这甚至不是解决我需要的正确方法。
Json数据:
data = [
{
"Name": "abc",
"Amount": 3000,
"Idnumber": "001",
"Date": "11/17/2017",
"Orders": [
{
"Order Number": "11",
"Date": "11/18/2017",
"Amount": 1000,
"Type": "test"
},
{
"Order Number": "12",
"Date": "12/31/2017",
"Amount": 2000,
"Type": "trial"
}
],
"foo": "foo",
"foo2": foo,
"foo3": "foo",
"foo4": "foo"
},
{
"Name": "def",
"Amount": 5000,
"Idnumber": "002",
"Date": "12/15/2017",
"Orders": [
{
"Order Number": "10",
"Date": "11/02/2017",
"Amount": 7600,
"Type": "trial"
},
{
"Order Number": "16",
"Date": "05/31/2018",
"Amount": 15000,
"Type": "interim"
}
],
"foo": "foo",
"foo2": foo,
"foo3": "foo",
"foo4": "foo"
}
]
最佳答案
您可以使用array#reduce
和array#map
将Idnumber
注入每个订单,随后再使用array#reduce
根据Type
对数据进行分组。
const data = [{"Name":"abc","Amount":3000,"Idnumber":"001","Date":"11/17/2017","Orders":[{"Order Number":"11","Date":"11/18/2017","Amount":1000,"Type":"test"},{"Order Number":"12","Date":"12/31/2017","Amount":2000,"Type":"trial"}],"foo":"foo","foo2":"foo","foo3":"foo","foo4":"foo"},{"Name":"def","Amount":5000,"Idnumber":"002","Date":"12/15/2017","Orders":[{"Order Number":"10","Date":"11/02/2017","Amount":7600,"Type":"trial"},{"Order Number":"16","Date":"05/31/2018","Amount":15000,"Type":"interim"}],"foo":"foo","foo2":"foo","foo3":"foo","foo4":"foo"}];
var result = data.reduce((r, {Orders, Idnumber}) => {
let orders = Orders.map(order => Object.assign({}, order, {Idnumber}));
return r.concat(orders);
},[]);
console.log(result);
console.log('--------------Grouped By----------');
var groupedBy = result.reduce((r,o) => {
r[o.Type] = r[o.Type] || [];
r[o.Type].push(o)
return r;
},{});
console.log(groupedBy);
.as-console-wrapper { max-height: 100% !important; top: 0; }