James Runner James Runner - 7 months ago 11
Javascript Question

JavaScript - Find objects by similar property and push it in a new array

I have the following JSON tree:

[
{
"category":"PASTAS",
"createdAt":"2016-01-01T19:47:57.813Z",
"currency":"$",
"dishName":"Spaghetti",
"estTime":"10-20 min",
"price":10,
"subName":"Pasta",
"updatedAt":"2016-04-28T20:48:06.800Z"
},
{
"category":"PIZZAS",
"createdAt":"2016-04-19T21:44:56.285Z",
"currency":"$",
"dishName":"Ai Funghi Pizza ",
"estTime":"20-30 min",
"price":20,
"subName":"Pizza",
"updatedAt":"2016-04-28T20:58:39.499Z"
},
{
"category":"PIZZAS",
"createdAt":"2016-04-19T21:44:56.285Z",
"currency":"$",
"dishName":"Seafood Pizza",
"estTime":"20-30 min",
"price":10,
"subName":"Pizza",
"updatedAt":"2016-04-28T20:58:39.499Z"
}
]


As you can see in the JSON tree the element
category:"PIZZAS"
repeats two times, what I would like to do is to either create a new array or organize these results in a way to avoid repetition in all the other duplicates, i.e. in the example above, I would have a final results like this:

Pastas:
Spaghetti

Pizza:
Ai Fungi Pizza,
Seafood Pizza


Any ideas on how to achieve the wanted result?

Answer

Assuming the array is named data, this should do the trick:

var result = {};                                       // Create an output object.
for(var i = 0; i < data.length; i++){                  // Loop over the input array.
    var row = data[i];                                 // Store the current row for convenience.
    result[row.category] = result[row.category] || []; // Make sure the current category exists on the output.
    result[row.category].push(row.dishName);           // Add the current dish to the output.
}
Comments