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
  • 322
  • 1
  • 4
  • 16

3 Answers3

3

Enclose id in square brackets:

createData = (image, text, id) => {
  return {
    [id]: {
      image,
      text,
    },
  };
};
Tim VN
  • 1,113
  • 1
  • 7
  • 16
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
  • 21,802
  • 5
  • 67
  • 87
1

Use the bracket notation like:

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

:)

Frede
  • 691
  • 4
  • 14