Skip to content Skip to sidebar Skip to footer

Format Grouped Data From Json Data

I am trying to format the grouped data that I got from JSON but having trouble doing that. This is my array of objects: arr = [ { 'date': '2020-01-01',

Solution 1:

Do something like that

Object.entries(personGroupedByColor).map(([key, group]) => ({
    ['date_val']: key,
    ['metric_name']: group.map(entry => entry.metric),
  }))

Solution 2:

You could reduce() the array and check if a given date is already in the accumulator, if so, push the current date to it, otherwise create a new object with that date in the array:

arr = [{
    date: "2020-01-01",
    metric: 32,
    type: "Google",
  },
  {
    date: "2020-01-01",
    metric: 24,
    type: "Bing",
  },
  {
    date: "2020-01-02",
    metric: 1,
    type: "Google",
  },
  {
    date: "2020-01-02",
    metric: 32,
    type: "Jeeves",
  },
  {
    date: "2020-01-03",
    metric: 24,
    type: "Bing",
  },
  {
    date: "2020-01-03",
    metric: 30,
    type: "Google",
  },
];

let result = arr.reduce((p, c) => {
  let match = p.find(o => o.date_val === c.date);
  if (match) {
    match.metric_name.push(c.metric)
  } else {
    p.push({
      date_val: c.date,
      metric_name: [c.metric],
    });
  }
  return p;
}, []);

console.log(result);

Solution 3:

You can use array.reduce and dynamically evaluate result keys based on specified fields:

let arr = [
            {
                "date": "2020-01-01",
                "metric": 32,
                "type": "Google"
            },
            {
                "date": "2020-01-01",
                "metric": 24,
                "type": "Bing"
            },
            {
                "date": "2020-01-02",
                "metric": 1,
                "type": "Google"
            },
            {
                "date": "2020-01-02",
                "metric": 32,
                "type": "Jeeves"
            },
            {
                "date": "2020-01-03",
                "metric": 24,
                "type": "Bing"
            },
            {
                "date": "2020-01-03",
                "metric": 30,
                "type": "Google"
            }
          ];
          
  letgroup = (arr, val, name) => arr.reduce((acc, curr) => {
      let valKey = val +"_val";
      let nameKey = name + "_name";
      let valValue = curr[val];
      let nameValue = curr[name];
      
      let existing = acc.find(x => x[valKey] === valValue);
      if(existing){
         existing[nameKey].push(nameValue);
      } else {
         acc.push({[valKey]: valValue, [nameKey]: [nameValue]})
      }
      return acc;
  }, []);
  
  console.log(group(arr, 'date', 'metric'))

Post a Comment for "Format Grouped Data From Json Data"