I was looking for a way to group an array of object by a field.
I found a very useful answer in the comments of this answer (by @tomitrescak : https://stackoverflow.com/a/34890276/7652464
function groupByArray(xs, key) {
return xs.reduce(function (rv, x) {
let v = key instanceof Function ? key(x) : x[key];
let el = rv.find((r) => r && r.key === v);
if (el) {
el.values.push(x);
}
else {
rv.push({ key: v, values: [x] });
}
return rv; }, []);
}
Which can be used as following
console.log(groupByArray(myArray, 'type');
This function works perfect, however, my array contains objects with embedded fields.
I would like to use the the function as following
console.log(groupByArray(myArray, 'fullmessage.something.somethingelse');
I already have a function for extracting the embedded fields which works.
function fetchFromObject(obj, prop) {
if(typeof obj === 'undefined') {
return '';
}
var _index = prop.indexOf('.')
if(_index > -1) {
return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
}
return obj[prop];
}
Which can be used as following
var obj = { obj2 = { var1 = 2, var2 = 2}};
console.log(fetchFromObject(obj, 'obj2.var2')); //2
Can somebody help my to implement my function into the the group function.