我有来自下面的json数据。目标是获取所有订单并将它们合并为一个数组,同时保持金额和IdNumber
,以便我可以在类型上使用lodash _.groupBy
。
最后,例如,我将使用每个IdNumber的Type:test和与该IdNumber对应的Order Amounts
我在数据上尝试了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是否跟踪了订单的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"
}
]
答案 0 :(得分:1)
newOrder = data.map(d => ({Orders: d.Orders, idNumber: d.Idnumber}))
答案 1 :(得分:1)
您可以使用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; }