0

how to pull data with one common field and make nested json in javascript

I have an array like this :

var arr = [{
    "date" : "2021-07-01",
    "Subject" : "Math",
    "index" : 1
},{
    "date" : "2021-07-02",
    "Subject" : "Social",
    "index" : 2
},{
    "date" : "2021-07-01",
    "Subject" : "Science",
    "index" : 3
},{
    "date" : "2021-07-02",
    "Subject" : "Economics",
    "index" : 4
},{
    "date" : "2021-07-01",
    "Subject" : "English",
    "index" : 5
},{
    "date" : "2021-07-02",
    "Subject" : "Computer",
    "index" : 6
}]

In Result I want an array like that

arr = [{
    date: "2021-07-01",
    data : [{subject : "Math", "index" : 1},{subject : "Science", "index" : 3},{subject : "English", "index" : 5}]
},{
    date: "2021-07-02",
    data : [{subject : "Social", "index" : 2},{subject : "Economics", "index" : 4},{subject : "Computer", "index" : 6}]
}]

Here is what I am trying

var checkData = [];
var resultArr;

for(var i=0; i<arr.length; i++){
    if(checkData.indexOf(arr[0].date) !== -1)  {
        // not getting data
    }else{
        checkData.push(arr[0].date);
        resultArr.date = arr[0].date;
        resultArr.data = {"index" : arr[0].index, "subject" : arr[0].subject};
        
    }
}

Any help how can I achive this.

pilchard
  • 12,414
  • 5
  • 11
  • 23
David
  • 4,266
  • 8
  • 34
  • 69
  • 1
    Does this answer your question? [Group array items using object](https://stackoverflow.com/questions/31688459/group-array-items-using-object) – pilchard Jul 05 '21 at 09:58
  • @pilchard Yes possibaly that is waht i was looking for. I tried but could'nt found that. closing my question – David Jul 05 '21 at 10:10
  • @pilchard here the second attribute i only color. But in my case I have more attribute to do – David Jul 05 '21 at 10:13
  • Yes, but the `group by` theory is the same, expand it to push the parts of your object you want. see this one if you need: [How to group an array of objects by key](https://stackoverflow.com/a/40774906/13762301) – pilchard Jul 05 '21 at 10:19

1 Answers1

-1
// fetch unique dates
const uniqueDates = arr.reduce((acc, rec) => {
  if(acc.includes(rec.date))
    return acc;
  return [...acc, rec.date]
}, [])

//build your object
const result = uniqueDates.reduce((acc, rec)=> {
  const data = arr.filter(i => i.date === rec).map(i => {
    delete i.date
    return i
  })
  
  return [...acc, {date: rec, data}]
  
}, [])

console.log(JSON.stringify(result, 2, 2))
Paul Zaslavskij
  • 638
  • 3
  • 9