I have an object array (coming from an XLSX.js parser, so its length and contents vary) representing grants that have been given to projects.
Simplified, it looks something like this:
var grants = [
{ id: "p_1", location: "loc_1", type: "A", funds: "5000" },
{ id: "p_2", location: "loc_2", type: "B", funds: "2000" },
{ id: "p_3", location: "loc_3", type: "C", funds: "500" },
{ id: "p_2", location: "_ibid", type: "D", funds: "1000" },
{ id: "p_2", location: "_ibid", type: "E", funds: "3000" }
];
I need to merge these into a new array that will look like this:
var projects = [
{ id: "p_1", location: "loc_1", type: "A", funds: "5000" },
{ id: "p_2", location: "loc_2", type: ["B", "D", "E"], funds: ["2000", "1000", "3000"] },
{ id: "p_3", location: "loc_3", type: "C", funds: "500" }
];
... so that when the id
is the same, it will merge the objects and combine some of their key values (in the example type
and funds
) into a simple sub-array. The other keys (location
) in these merged objects inherit the values from the first instance and ignore the rest.
After several failed attempts and a lot of searching online, I got an idea from this answer to loop through grants
like this:
var res = {};
$.each(grants, function (key, value) {
if (!res[value.id]) {
res[value.id] = value;
} else {
res[value.id].type = [res[value.id].type, value.type];
res[value.id].funds = [res[value.id].funds, value.funds];
}
});
var projects = []
projects = $.map( res, function (value) { return value; } );
It actually works perfectly, EXCEPT that as I need an array, I removed .join(',')
from the ends (from the answer mentioned above), which in turn has created the problem I can't seem to solve now. The sub-arrays become nested in each other somehow if there is at least three items in them! I sort of understand why (the loop), but I wonder if there is a way to convert all these little multi-dimensional arrays inside the objects into sigle arrays (like: type: ["B", "D", "E"]
)?
var grants = [
{ id: "p_1", location: "loc_1", type: "A", funds: "5000" },
{ id: "p_2", location: "loc_2", type: "B", funds: "2000" },
{ id: "p_3", location: "loc_3", type: "C", funds: "500" },
{ id: "p_2", location: "_ibid", type: "D", funds: "1000" },
{ id: "p_2", location: "_ibid", type: "E", funds: "3000" }
];
var res = {};
$.each(grants, function (key, value) {
if (!res[value.id]) {
res[value.id] = value;
} else {
res[value.id].type = [res[value.id].type, value.type];
res[value.id].funds = [res[value.id].funds, value.funds];
}
});
var projects = []
projects = $.map( res, function (value) { return value; } );
$("pre").html(JSON.stringify(projects,null,2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="json"></pre>