1

I am curious if it is possible to assign a variables value to be a properties name in a Javascript object. For example, If I want to make objects where the key is a timestamp.

const timestamp = Date.now().toString();
const myObject = {
    timestamp: {
        data: "data value",
        data2: 2,
        . . .
        }
};

and output being something like

1686151152733: { data: "data value", data2: 2, ... }
Caleb Renfroe
  • 183
  • 1
  • 13

4 Answers4

1

Just use the bracket notation, also known as a Computed Property Name

const timestamp = Date.now().toString();
const myObject = {
    [timestamp]: {
        data: "data value",
        data2: 2,
    }
};

console.log(myObject);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
0

If you want to dynamically assign your timestamp as an object key, you'll need to use the dynamic access to access a key. (access a property dynamically with brackets)

you'd be able to do like this:

const timestamp = Date.now().toString();
const myObject = {
    [timestamp]: {
        data: "data value",
        data2: 2,
        // ...
    }
};
nook
  • 1,729
  • 1
  • 12
  • 34
0

I apologize if I didn't fully understand your question. Here is a code snippet that might be helpful.

const timestamp = Date.now().toString();
const myObject = {
    [timestamp]: {
        data: "data value",
        data2: 2,
        },
        
        
};



for (var key in myObject) {
  console.log(key, myObject[key]);
}
Abshir M
  • 41
  • 7
-1

Yes, you need to do it like this:

const myObject = {
    [timestamp]: {
        data: "data value",
        data2: 2,
        . . .
        }
};
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367