Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append values to javascript dictionary

Tags:

javascript

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
}
like image 297
turtle Avatar asked Oct 25 '13 21:10

turtle


2 Answers

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.

like image 55
Barmar Avatar answered Sep 28 '22 07:09

Barmar


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] }), {})
like image 33
l30.4l3x Avatar answered Sep 28 '22 06:09

l30.4l3x