-1

I don't know if its even possible but I'm wondering if you can add a const as an object property for an object.

So for example something like this:

const x = "age";

let array = {
name : "Tom",
x: "15";
}

So, in my case adding a new property to the object called 'age'. Where x is the variable that was already defined.

This is probs a dumb question but thanks in advance :)

pilchard
  • 12,414
  • 5
  • 11
  • 23
kzehrt
  • 1

2 Answers2

1

try this code :

const x = "age";

let array = {
name : "Tom",
[x]: "15";
}
Nokwiw
  • 386
  • 4
  • 11
1

You can use a computed property name

const key = "age";
const value = 15;

let object = {
  name : "Tom",
  [key]: value
}

console.log(object);

But you can also take advantage of the shorthand notation by declaring a property that will take the name of the variable passed as well as assign its value to the property.

const age = 15;

let object = {
  name : "Tom",
  age
}

console.log(object);
pilchard
  • 12,414
  • 5
  • 11
  • 23