1 回答

TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以data使用 as 鍵將數(shù)組縮減為一個(gè)對(duì)象shipping.addresses.id,并使用 返回一個(gè)數(shù)組Object.values()。您將需要迭代addresses每個(gè)對(duì)象的數(shù)組,并在遇到每個(gè)對(duì)象時(shí)為每個(gè)對(duì)象創(chuàng)建一個(gè)條目id,并推送到這些條目以獲取具有相同id.
const byAddressId = Object.values(
data.reduce((a, o) => {
o.shipping.addresses.forEach(({id, area}) => {
a[id] = {...a[id] ?? {id: id, area: area, data: []}};
a[id]['data'].push({...o});
});
return a;
}, {}));
const data = [{"email": "alex@test.com","fn": "Alex","sn": "McPherson","phone": "01233xxxxx","hours": "40","rate": "20","amount": "200","vat": "60","agency": "test","start": "08/06/2017","end": "10/06/2017","shipping": { "addresses": [ { "id": "1234", "area": "xzy" }, { "id": "2345", "area": "uhj" } ]}},{"email": "mike@test.com","fn": "Mike","sn": "Mann","phone": "01233xxxxx","hours": "50","rate": "70","amount": "500","vat": "90","agency": "test","start": "08/06/2017","end": "10/06/2017","shipping": { "addresses": [ { "id": "1234", "area": "xzy" }, { "id": "3456", "area": "uio" } ]}},{"email": "fred@test.com","fn": "Fred","sn": "Frogg","phone": "01233xxxxx","hours": "80","rate": "90","amount": "800","vat": "100","agency": "test","start": "08/06/2017","end": "10/06/2017","shipping": { "addresses": [ { "id": "4567", "area": "asdaf" }, { "id": "3456", "area": "uio" } ]}},{"email": "alex@test.com","fn": "Alex","sn": "McPherson","phone": "01233xxxxx","hours": "90","rate": "30","amount": "900","vat": "120","agency": "test","start": "08/06/2017","end": "10/06/2017","shipping": { "addresses": [ { "id": "4567", "area": "asdaf" }, { "id": "5678", "area": "asdf" } ]}}];
// return array of Object.values from the accumulator
const byAddressId = Object.values(
// reduce the data array into an object with shipping.addresses.id as keys
data.reduce((a, o) => {
// iterate over all addresses for each element
o.shipping.addresses.forEach(({id, area}) => {
// check if an id entry exists, otherwise create one
a[id] = {...a[id] ?? {id: id, area: area, data: []}};
// push the object to the data array of the id object
a[id]['data'].push({...o});
});
return a;
}, {}));
console.log(byAddressId);
話雖這么說,與問題中包含的示例map()
相比,您可以使用相同的方法來節(jié)省兩次調(diào)用。group by email
const byEmail = Object.values( data.reduce((a, o) => (a[o.email] = [...a[o.email] ?? [], {...o}], a), {}));
添加回答
舉報(bào)