2

I have an array of strings that I get from an endpoint and I need to convert it to key-value pairs for the frontend to display them correctly. I have tried different concepts such as reduce and map but have not been able to get it working successfully. I assume it might be one-liner for someone familiar with FE but has taken forever for a BE person like me.

Here is what I have tried:

var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => {"id":x, "label":x};);
console.log(mapping);

I am expecting an output of the format

[{"id":"quiz1", "label":"quiz1"}, {"id":"quiz2", "label":"quiz2"}]

Thanks for looking!

user1596115
  • 321
  • 1
  • 5
  • 17

1 Answers1

3

It's simply two syntax errors:

var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => ({"id":x, "label":x}));
console.log(mapping);
  1. Firstly, no semicolon in a un-braced arrow function body.

    This is invalid: (() => 3;). This is valid: (() => 3).

  2. Secondly, wrap return obj in ().

    This is invalid: () => {x: 3}. This is valid: () => ({x: 3}).

Community
  • 1
  • 1
junvar
  • 11,151
  • 2
  • 30
  • 46