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?
An associative array is declared or dynamically createdWe can create it by assigning a literal to a variable. var arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.
An associative array maps unique keys to values that can be non-unique. An associative array is also called a dictionary, a map, a hash map, or a hash table.
An associative array is an array with string keys rather than numeric keys. Associative arrays are dynamic objects that the user redefines as needed. When you assign values to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and methods of Array.
The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.
You may use Array.prototype.reduce
for your task. It allows a return value in the callback function for the next call.
var data = [
{ 'list': 'one', 'item': 1 },
{ 'list': 'one', 'item': 2 },
{ 'list': 'one', 'item': 3 },
{ 'list': 'two', 'item': 1 },
{ 'list': 'two', 'item': 2 }
],
flat = data.reduce(function (r, a) {
r[a.list] = r[a.list] || [];
r[a.list].push(a.item);
return r;
}, {});
document.write('<pre>' + JSON.stringify(flat, 0, 4) + '</pre>');
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
});
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