I'm currently working on a task that involves creating an array to summarize another array. I've received valuable suggestions from various sources, including this discussion on Stack Overflow. Although the solutions provided are effective, they present new challenges that I am struggling to overcome.
Thanks to @kooiinc's response, my code now looks 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" }
];
var projects = [];
grants.map(
function (v) {
if (!(v.id in this)) {
this[v.id] = v;
projects.push(v);
} else {
var current = this[v.id];
current.type = [v.type].concat(current.type);
current.funds = [v.funds].concat(current.funds);
}
}, {});
... resulting in the desired output (type
and funds
combined into sub-arrays, while other properties remain unchanged):
[
{ "id": "p_1", "location": "loc_1", "type": "A", "funds": "5000" },
{ "id": "p_2", "location": "loc_2", "type": ["E","D","B"], "funds": ["3000","1000","2000"] },
{ "id": "p_3", "location": "loc_3", "type": "C", "funds": "500" }
]
However, when certain objects contain undefined key values, the result includes nulls in the arrays as shown below (observe the type
array):
[
{ "id": "p_1", "location": "loc_1", "type": "A", "funds": "5000" },
{ "id": "p_2", "location": "loc_2", "type": ["E",null,null], "funds": ["3000","1000","2000"] },
{ "id": "p_3", "location": "loc_3", "type": "C", "funds": "500" }
]
(For a demonstration, refer to this fiddle.)
I attempted to remove these null values using methods like the ones mentioned here or here, but unfortunately, none of them seemed to work effectively despite being implemented at different stages in my code. These methods did not produce any errors, but they simply did not eliminate the null values.
Is there a way to exclude undefined keys during the mapping process itself?
Update: Some object keys may have no values at all, only containing [null,null,null]
, while others might have some filled values alongside null entries such as ["E",null,null]
. The aim is to filter out all null items, subsequently removing the entire key if it contains no remaining values.