0

I am using a database and I want to store items that a user has in an object. How would I push a variable's value into a name of an object's value?

Code example:

let item = 'test'
items.push({item: other})
shaedrich
  • 5,457
  • 3
  • 26
  • 42
Pixel445
  • 33
  • 5
  • In your specific case: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names , or just `items.push({item});`, when you need to assign `other` to `item`. – Teemu Jun 24 '21 at 08:54
  • What is `items` in this scenario and how would you like it to look after you've done the "push"? I'd like to understand your requirements but I don't – byxor Jun 24 '21 at 08:56

2 Answers2

0

You can set the key of an object to be the value of a variable like this:

let item = 'test';
items.push({[item]: "foobar"});

Your result will look like this: {test: "foobar"}

Nils Fahle
  • 126
  • 1
  • 8
0

Is this what you are looking for?

let item = "test";
let items = [];
items.push({
  [item]: "other"
})

console.log(items);
Behemoth
  • 5,389
  • 4
  • 16
  • 40