我正在嘗試對陣列元素進行分組(包含訂單詳細資訊)。這是我的陣列結構:

[{"id":"myid","base":{"brands":["KI", "SA"],"country":"BG","status":"new"}},{"id":"DEC-00500331","base":{"brands":["DEC"],"country":"UK","status":"new"},"psp":{"name":"adyen","status":"paid"}}]
訂單與國家網站相關,可以包含一個或多個品牌。例如,在一個訂單中,我可以擁有來自brand1 的商品和來自brand2 的商品。
我需要按國家和品牌對這些訂單進行分組,這樣我就可以擁有一個合并的陣列或物件。
我可以很容易地按國家分組:
let groupedDataByCountryAndBrand = _.groupBy(orders.value, 'base.country')
Object.keys(groupedDataByCountryAndBrand).forEach(key => {
table.push(
{
country : key, //to be reviewd : for the two brands or more in one order
new : groupedDataByCountryAndBrand[key].filter( order => (order.base.status === SFCC_STATUS.new
|| SFCC_STATUS.open
|| SFCC_STATUS.completed )).length
})
})
這是結果:

不幸的是,這對我不起作用。我需要按國家和品牌對訂單進行分組,以便按國家統計每個品牌的新訂單。
我期待的結果是這樣的:
{
"country" : "FR",
"brand": "adidas",
"pending": 4
"new" : 3,
"an other status": 5
}
你知道我怎么能做到這一點嗎?
我正在使用帶有 vue 組件的 lodash。謝謝。
uj5u.com熱心網友回復:
這是您正在尋找的內容,而無需使用任何其他庫:
const data = [{"id":"myid","base":{"orderNumber":"0500332","marketPlaceOrderCode":"","creationDate":"2022-06-14T10:49:10Z","source":"sfcc","brands":["KI", "SA"],"country":"BG","status":"new","totalEuro":12,"currency":"BGN","units":1,"coupons":null,"shipping":{"id":"BG01","name":"Speedy COD","status":"not_shipped"}},"psp":{"name":"payu","method":null,"status":null},"tms":null},{"id":"DEC-00500331","base":{"orderNumber":"id2","marketPlaceOrderCode":"","creationDate":"2022-06-14T10:41:29Z","source":"sfcc","brands":["DEC"],"country":"UK","status":"new","totalEuro":57,"currency":"GBP","units":1,"coupons":null,"shipping":{"id":"ECA_DPD_ST","name":"Standard shipping","status":"not_shipped"}},"psp":{"name":"adyen","method":null,"status":"paid"},"tms":null}];
const rawResult = normalizeData(data);
console.log(makeItReadable(rawResult));
function normalizeData(data) {
const result = {};
data.forEach((order) => {
const orderData = order.base;
// add country to result (if not exists)
if (!result[orderData.country]) {
result[orderData.country] = {};
}
orderData.brands.forEach((brand) => {
// add brand to exact country (if not exists)
if (!result[orderData.country][brand]) {
result[orderData.country][brand] = {};
}
// add status to exact brand and country (if not exists)
if (!result[orderData.country][brand][orderData.status]) {
result[orderData.country][brand][orderData.status] = 0;
}
// increment status count
result[orderData.country][brand][orderData.status];
});
});
return result;
}
function makeItReadable(rawData) {
const readableResult = [];
Object.keys(rawData).map((country) => {
Object.keys(rawData[country]).map((brand) => {
readableResult.push({country, brand, ...rawData[country][brand]});
});
});
return readableResult;
}
此代碼將為您提供以下結果:
[
{ country: 'BG', brand: 'KI', new: 1 },
{ country: 'BG', brand: 'SA', new: 1 },
{ country: 'UK', brand: 'DEC', new: 1 }
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/490675.html
標籤:javascript 数组 Vue.js 通过...分组
上一篇:添加不同維度的陣列
