Home > database >  create new array of object with keys from data, base on array of object with condition
create new array of object with keys from data, base on array of object with condition

Time:01-17

const October = [
  {
    event_category: 'EVENT',
    date: '2022-10-02',
    detail: 'event',
  },
  {
    event_category: 'TASK',
    date: '2022-10-03',
    detail: 'task',
  },
  {
    event_category: 'EVENT',
    date: '2022-10-04',
    detail: 'event 1',
  },
  {
    event_category: 'TASK',
    date: '2022-10-04',
    detail: 'task 1',
  },
  {
    event_category: 'TASK',
    date: '2022-10-04',
    detail: 'task 2',
  },
];

is there a method with map or reduce to create new array of object like this. i have try method with object assign etc.. cant solve it.

the result i want.

const newOct = [
  {
    '2022-10-02': {
      event_category: 'EVENT',
      date: '2022-10-02',
    },
    '2022-10-03': {
      event_category: 'TASK',
      date: '2022-10-03',
    },
    '2022-10-04': {
      event_category: 'TASK_EVENT',
      date: '2022-10-04',
    },
  },
];

CodePudding user response:

You achieve it by using following code

const October = [
    {
        event_category: 'EVENT',
        date: '2022-10-02',
        detail: 'event',
    },
    {
        event_category: 'TASK',
        date: '2022-10-03',
        detail: 'task',
    },
    {
        event_category: 'EVENT',
        date: '2022-10-04',
        detail: 'event 1',
    },
    {
        event_category: 'TASK',
        date: '2022-10-04',
        detail: 'task 1',
    },
    {
        event_category: 'TASK',
        date: '2022-10-04',
        detail: 'task 2',
    },
];

function onlyUnique(value, index, self) {
    return self.indexOf(value) === index;
}

let newOct = [{}];
let dates = October.map(item => item.date);
dates = dates.filter(onlyUnique);

for (let date of dates) {
    let event_category = ''; 
    for (let item of October) {
        if (item.date === date) {
            event_category = event_category ? event_category.includes(item.event_category) ? event_category : event_category   "_"   item.event_category : item.event_category;
        }
    }
    newOct[0][date] = { event_category, date };
}
console.log('newOct: ', newOct);

  • Related