I'm trying to develop a group-by function for an object, where I can group an array based on a field and then merge all fields of the grouped documents from the array with their corresponding group-object fields.
const groupInDoc = (array, fieldname) => {
let groupedResultDoc = array.reduce((carDocs, current) => {
let keyCount = Object.keys(current).length;
let obj = {};
for (let [key, value] of Object.entries(current)) {
console.log(`${key}: ${value}`);
//check if key matches the field name to group by.
if (key == fieldname) {
} else {
obj[key] = value;
}
}
if (carDocs.hasOwnProperty(current[fieldname])) {
carDocs[current[fieldname]] = obj;
} else {
carDocs[current[fieldname]] = obj;
}
return carDocs;
}, Object.create({}));
return groupedResultDoc;
}
I am facing a challenge in how to expand the fields of the grouped objects using other corresponding object fields from the array objects.
For example, if my grouped object includes a subdocument for a group key with an array field and a string field, I want to add new values from matching group objects to the existing array and combine strings together using "+". How can I achieve this?
UPDATE: Original data:
let doc = [
{
"car": "Ford",
"prices": ["12", "3", "5", "1"],
"model": "SUV"
},
{
"car": "Ford",
"prices": ["99","88","77"],
"model": "T3"
},
{
"car": "Toyota",
"prices": ["33","44","55"],
"model": "Subaru"
},
{
"car": "Toyota",
"prices": ["66", "50", "22"],
"model": "Cheyenne"
},
{
"car": "Peugeot",
"prices": ["1","2","3"],
"model" : "503"
}
];
The current result is:
CarDocs: { Ford: { prices: [ '99', '88', '77' ], model: 'T3' },
Toyota: { prices: [ '66', '50', '22' ], model: 'Cheyenne' },
Peugeot: { prices: [ '1', '2', '3' ], model: '503' } }
but it should be:
CarDocs: { Ford: { prices: ["12", "3", "5", "1", '99', '88', '77' ], model: 'T3', 'SUV' },
Toyota: { prices: [33","44","55", '66', '50', '22' ], model: 'Cheyenne', 'Subaru' },
Peugeot: { prices: [ '1', '2', '3' ], model: '503' } }