0

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',
}

2 Answers 2

2

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 });

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.