0

I have a function that creates objects, but I want to receive the key for that object by parameter. How do I set this key? When I put the parameter the function does not take and sets the name of that parameter as the key

enter image description here

My code:

createData = (image, text, id) => {
  return {
    id: {
      image,
      text,
    },
  };
};
LayTexas
  • 545
  • 2
  • 6
  • 19

3 Answers3

3

Enclose id in square brackets:

createData = (image, text, id) => {
  return {
    [id]: {
      image,
      text,
    },
  };
};
Tim VN
  • 1,183
  • 1
  • 7
  • 19
3

Enclose the variable that you want to use as the property with square brackets, like so:

createData = (image, text, id) => {
  return {
    [id]: {
      image,
      text,
    },
  };
};
sdgluck
  • 24,894
  • 8
  • 75
  • 90
1

Use the bracket notation like:

createData = (image, text, id) => {
  return {
    [id]: {
      image,
      text,
    },
  };
};

:)

Frede
  • 701
  • 4
  • 14