简体   繁体   中英

Best way restructure object in JS

I have array of objects, width date and time property like below. I try restructure elements by day and time.

[
  {
    data: 'data1',
    date: '15-02-2020 06:00:00'
  },
  {
    data: 'data2',
    date: '15-02-2020 12:00:00'
  },
  ...
  {
    data: 'data6',
    date: '17-02-2020 07:00:00'
  },
  {
    data: 'data7',
    date: '17-02-2020 09:00:00'
  }
]

I want to get this:

{
  '15-02-2020' : {
    '06:00:00' : 'data1',
    '12:00:00' : 'data2'
  },
  '16-02-2020' : {
    '06:00:00' : 'data3',
    '12:00:00' : 'data4'
  },
  '17-02-2020' : {
    '01:00:00' : 'data5',
    '07:00:00' : 'data6',
    '09:00:00' : 'data7'
  }
}

I tried use reduce , but cant. I want do that, without temporary variables in one loop.

list.reduce((obj, item) => Object.assign(obj, {[item.date]: item}), {});

Just loop through your array and build the result object dynamically:

 const arr = [ { data: 'data1', date: '15-02-2020 06:00:00' }, { data: 'data2', date: '15-02-2020 12:00:00' }, { data: 'data6', date: '17-02-2020 07:00:00' }, { data: 'data7', date: '17-02-2020 09:00:00' } ] const res = {} arr.forEach(item => { const dateArr = item.date.split(' ') if (res[dateArr[0]]) { res[dateArr[0]][dateArr[1]] = item.data } else { res[dateArr[0]] = {} res[dateArr[0]][dateArr[1]] = item.data } }) console.log(res)

You could reduce the array, split date and use the day ad key for another object.

 var data = [{ data: 'data1', date: '15-02-2020 06:00:00' }, { data: 'data2', date: '15-02-2020 12:00:00' }, { data: 'data6', date: '17-02-2020 07:00:00' }, { data: 'data7', date: '17-02-2020 09:00:00' }], result = data.reduce((r, { data, date }) => { const [day, time] = date.split(' '); r[day] = r[day] || {}; r[day][time] = data; return r; }, {}); console.log(result);

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