I want to group the objects that have same skuinfo.billFreq together from this array of objects. The skusList is an array of objects. It has objects 0,1,2,3...and so on. These objects further have object called skuinfo in them. I want to group the outer objects(named as 0,1,2...) according to the skuinfo.billfreq. This the array:
skusList: [{,…}, {,…}, {,…}, {,…}, {,…}, {,…}]
0: {,…}
description: ""
skuid: "b7d83836-54d0-480c-9334-7fb90e7b5879"
skuinfo: {skunumber: "prepaidtest2", price: "675.00", currency: "USD", billfreq: "PREPAID", termlength: 1,…}
billfreq: "PREPAID"
currency: "USD"
ismonthlyskuenabled: false
monthlyskunumber: ""
price: "675.00"
pricemeasurementunitList: ["12"]
skunumber: "prepaidtest2"
termlength: 1
unitofmeasurement: "Year"
status: "pending"
1: {,…}
description: ""
skuid: "52855053-fb97-4ecd-8d9c-75642135cc90"
skuinfo: {skunumber: "prepaidtest", price: "123.00", currency: "USD", billfreq: "PREPAID", termlength: 1,…}
billfreq: "PREPAID"
currency: "USD"
ismonthlyskuenabled: false
monthlyskunumber: ""
price: "123.00"
pricemeasurementunitList: ["1"]
skunumber: "prepaidtest"
termlength: 1
unitofmeasurement: "Year"
status: "pending"
2: {,…}
3: {,…}
4: {,…}
5: {,…}
I was trying to use the groupBy() method, but it doesn't take the nested property of the object. Can someone help?
CodePudding user response:
Here's some example of the groupBy method from mdn site. Try this:-
let result = yourArr.groupBy( ({ billfreq }) => billfreq );
CodePudding user response:
If you don't want to use libraries, I just changed this code to group by nested property:
let myArr = [{ description: "", skuid: "b7d83836-54d0-480c-9334-7fb90e7b5879", skuinfo: {skunumber: "prepaidtest2", price: "675.00", currency: "USD", billfreq: "PREPAID", termlength: 1}, billfreq: "PREPAID", currency: "USD", ismonthlyskuenabled: false, monthlyskunumber: "", price: "675.00", pricemeasurementunitList: ["12"], skunumber: "prepaidtest2", termlength: 1, unitofmeasurement: "Year", status: "pending", },{ description: "", skuid: "52855053-fb97-4ecd-8d9c-75642135cc90", skuinfo: {skunumber: "prepaidtest", price: "123.00", currency: "USD", billfreq: "PREPAID", termlength: 1}, billfreq: "PREPAID", currency: "USD", ismonthlyskuenabled: false, monthlyskunumber: "", price: "123.00", pricemeasurementunitList: ["1"], skunumber: "prepaidtest", termlength: 1, unitofmeasurement: "Year", status: "pending", }];
var groupBy = function(xs, key, subkey) {
return xs.reduce(function(rv, x) {
let keyToGroup = x[key][subkey] ?? x[key];
(rv[keyToGroup] = rv[keyToGroup] || []).push(x);
return rv;
}, {});
};
console.log(groupBy(myArr, "skuinfo", "billfreq"));
Note: this works also for not nested properties.