Append values to javascript dictionary

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] }), {})

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 way, with reduce.

var d = input.reduce(function (res, item) {
    var key = item.key;

    if (!res[key]) res[key] = [item.val];
    else res[key].push(item.val);

    return res;

}, {});

Tags:

Javascript