mrks
mrks

Reputation: 5631

Use switch case for array of objects

I have the following array (transposed) given:

[
  [ 'Holiday', 'Date', 'Typ' ],
  [ 'Neujahr', 44197, 'FIXED' ],
  [ 'Heilige Drei Könige', 44202, 'REOCCURING' ],
  [ '…', '…', '…' ]
]

What I need:

{
  "holidays": [
    {
      "name": "Neujahr",
      "date": "01.01.2021",
      "type": "RECURRING"
    },
    ...
  ]
}

What I tried to use is this switch case:

const output: any = index.reduce((acc: any, curr: number, idx: number) => {
  switch (curr) {
    case 0:
      acc.name = transposed[1][0];
      break;
    case 1:
      acc.date = DateTimeUtil.xlDateConvert(transposed[idx][1]);
      break;
    case 2:
      acc.type = transposed[idx][2];
      break;
    default:
      break;
  }
  return acc;
}, {});

But this does not work as I get this as a result:

{
  name: 'Neujahr',
  date: '2021-01-01T00:00:00.000Z',
  type: 'REOCCURING',
}

Upvotes: 0

Views: 1202

Answers (2)

Akxe
Akxe

Reputation: 11555

You did overcomplicate things quite a lot. You don't need a reduce at all. You only want to map array to object.

const input = [
  [ 'Holiday', 'Date', 'Typ' ],
  [ 'Neujahr', 44197, 'FIXED' ],
  [ 'Heilige Drei Könige', 44202, 'REOCCURING' ],
];

// input.slice(1) // get rid of first row
const output = input.slice(1).map(([name, time, type]) => {
  return { 
    name,
    time: time, // DateTimeUtil.xlDateConvert(time)
    type,
  };
});

console.log({ holidays: output });

Upvotes: 2

KooiInc
KooiInc

Reputation: 122936

Maybe you don't need switch?

const [holidays, name, date, type] = 'holidays,name,date,type'.split(',');
const arr = [
    [ 'Neujahr', 44197, 'FIXED' ],
    [ 'Heilige Drei Könige', 44202, 'REOCCURING' ], 
  ].reduce( (acc, val) =>
     ( { ...acc, 
         [holidays]: [...acc[holidays], { 
           [name]: val[0], 
           [date]: val[1] /* raw */, 
           [type]: val[2]} ] } 
     ), { [holidays]: [] } );
     
console.log(arr);

Upvotes: 1

Related Questions