I am trying to create the following data structure in javascript:
d = {"foo": [3, 77, 100], "bar": [10], "baz": [99], "biff": [10]}
My starting data structure is a a list of dictionaries:
input = [{"key": "foo", "val": 3}, {"key": "bar", "val": 10}, {"key": "foo", "val": 100}, {"key": "baz", "val": 99}, {"key": "biff", "val": 10}, {"key": "foo", "val": 77]
How can I generate my desired data structure? The following code doesn't seem to append values to the value array.
var d = {}
for (var i in input) {
var datum = input[i];
d[datum.key] = datum.val
}
for (var i = 0; i < input.length; i++) {
var datum = input[i];
if (!d[datum.key]) {
d[datum.key] = [];
}
d[datum.key].push(datum.val);
}
FYI, you shouldn't use for (var i in input)
to iterate over an array.
Another alternative:
const input = [{ "key": "foo", "val": 3 }, { "key": "bar", "val": 10 }, { "key": "foo", "val": 100 }, { "key": "baz", "val": 99 }, { "key": "biff", "val": 10 }, { "key": "foo", "val": 77 }]
const dict = {}
input.forEach(({ key, val }) =>
key in dict ? dict[key].push(val) : dict[key] = [val] )
console.log(dict);
And a one-liner, with immutability
input.reduce((dict, { key, val }) => ({ ...dict, [key]: [...dict[key] || [], val] }), {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With