javascript add to a dictionary 1

javascript add to a dictionary

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);
}

Here is what the above code is Doing:
1. We're creating a dictionary called d.
2. We're iterating through the input array.
3. For each element in the input array, we're checking if the key exists in the dictionary. If it doesn't, we're creating an empty array for that key.
4. We're pushing the value of the element into the array for that key.

The output of the above code is:
{
"a": [1, 2, 3],
"b": [4, 5, 6],
"c": [7, 8, 9]
}

Similar Posts