简体   繁体   中英

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

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.

// 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM