Search code examples
javascriptarraysassociative-arraymap-function

Creating an associative array in JavaScript using the map function


I've an array of objects with the following format

[{'list': 'one', 'item': 1},
 {'list': 'one', 'item': 2},
 {'list': 'one', 'item': 3},
 {'list': 'two', 'item': 1},
 {'list': 'two', 'item': 2}]

And I want to transform it like this

[{'one': [1, 2, 3]},
 {'two': [1, 2]}]

How can I do it using the Array.map function? Is it the best alternative?


Solution

  • To your specific question:

    // Let x hold your array of objects.
    
    res={}; // Create an empty object that will hold the answer
    
    x.forEach (function (e) { // Use this function to iterate over each item in the list
        res[e.list] = res[e.list] || [];   // inspired by the Nina Scholz answer below
        res[e.list].push(e.item);   // Append the result to the array
     });