I needed a way to group an array of objects by a specific field.
Fortunately, I came across a valuable solution in the comments section of this post (by @tomitrescak:
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; }, []);
}
This function works perfectly fine for me, but my array has objects with nested fields.
I want to use the function like this
console.log(groupByArray(myArray, 'fullmessage.something.somethingelse');
Thankfully, I already have a function that extracts nested fields successfully.
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];
}
You can use it like this
var obj = { obj2 = { var1 = 2, var2 = 2}};
console.log(fetchFromObject(obj, 'obj2.var2')); //2
Could someone assist me in integrating my function into the grouping function?