Skip to content Skip to sidebar Skip to footer

How To Iterate An Array Of Objects And Group The Property Values By Their Key Name?

I have an array of objects named data, like so: data = [{'timeslot':'7pm-8pm','Monday':60,'Tuesday':55}, {'timeslot':'8pm-9pm','Monday':70,'Tuesday':60}, {'timeslot

Solution 1:

Basicall you are overwiting the last result with a new array

result[key.toLowerCase()] = [obj[key]];
// ^^^^^^^^^^^^^^^^^^^^^^   ^        ^

But you need only one array for a key and the push the actual value, like

result[key] =result[key] || []; //createarray, if not exist
result[key].push(o[k]);          // push value

Working code:

var data = [{ timeslot: "7pm-8pm", Monday: 60, Tuesday: 55 }, { timeslot: "8pm-9pm", Monday: 70, Tuesday: 60}, { timeslot: "9pm-10pm", Monday: 40, Tuesday: 37 }],
    result = {};

data.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        var key = k.toLowerCase();
        result[key] = result[key] || [];
        result[key].push(o[k]);
    });
});

console.log(result);

Solution 2:

The issue with your code is that, while you are iterating over the keys array, you are replacing the previous value each time here

result[key.toLowerCase()] = [obj[key]];  // This is replacing the existing value

To add a new entry to an array, you can use Array.push() method as shown below :

result[key.toLowerCase()].push([obj[key]]);

var data = [{"timeslot":"7pm-8pm","Monday":60,"Tuesday":55},{"timeslot":"8pm-9pm","Monday":70,"Tuesday":60},{"timeslot":"9pm-10pm","Monday":40,"Tuesday":37}];

var result = {}; 

data.map(function (each) {
  Object.keys(each).map(function (key){
    result[key] = result[key] || [];
    result[key].push(each[key]);
  });

});

console.log(result);

Post a Comment for "How To Iterate An Array Of Objects And Group The Property Values By Their Key Name?"