So, I have an indeterminate amount of arrays in an object, and I need to merge the objects in them. The arrays are guaranteed to be the same length, and the objects are guaranteed to have the same keys.
I've tried iterating through it, though for some reason, it sums the objects in every key in the array.
Example:
var demo = {
"key1": [{"a": 4, "b": 3, "c": 2, "d": 1}, {"a": 2, "b": 3, "c": 4, "d": 5}, {"a": 1, "b": 4, "c": 2, "d": 9}]
"key2": [{"a": 3, "b": 5, "c": 3, "d": 4}, {"a": 2, "b": 9, "c": 1, "d": 3}, {"a": 2, "b": 2, "c": 2, "d": 3}]
};
mergeArrays(demo);
/* Returns:
{
"arbitraryname": [{"a": 7, "b": 8, "c": 5, "d": 5}, {"a": 4, "b": 12, "c": 5, "d": 8}, {"a": 3, "b": 6, "c": 4, "d": 12}]
}
*/
My current implementation attempts to do something like this:
var skeleton = {
"a": 0,
"b": 0,
"c": 0,
"d": 0
};
function mergeArrays = function (obj) {
var flat = {};
var keys = _.keys(prod);
var len = obj[keys[0]].length;
flat["arbitraryname"] = [];
for (var i = 0; i < len; i++) {
flat["arbitraryname"].push(skeleton);
}
flat["arbitraryname"].forEach(function (v, k) {
_.forIn(v, function (key, value) {
flat["arbitraryname"][k][key] += value;
});
});
return flat;
}
Is there any easier way to do that? It also appears to return an array right now that's entirely identical. E.g.:
[{"a": 14, "b": 26, "c": 14, "d": 25}, {"a": 14, "b": 26, "c": 14, "d": 25}, {"a": 14, "b": 26, "c": 14, "d": 25}]
Where each object is a sum of ALL elements in the array. What am I doing wrong? Is there an easier way?
JSON.parse(JSON.stringify(skeleton)). I also found a solution that works that's similar, but not exact. I'll try and post it tonight.