How to save dynamic key reference when creating an object in javascript?

Viewed 216

Is there a way to make this happen during an object initiation?

//uuid() returns a new uuid
let Obj = {
  [uuid()]:{
    id: (get the ID that was just created)
  }
}

so the output should be something like

Obj {
  5cb93583: {
  id: 5cb93583
  }
}
3 Answers

You could use an immediately invoked (arrow) function, together with some other ES6 syntax:

let obj = (id => ({ [id]: {id} }))(uuid());

As a side note: better use camelCase for variable names, and reserve the initial-capital notation only for constructors/classes.

Yes, You can simply use a variable to store the uuid() and then,

let key = uuid();
let obj = {
   [key]:{
      id: key
   }

make sure that you key is string

Beside the given IIFE, you could take a explicit function for it, because this approach is reusable.

const
    getUUID = _ => Math.floor(Math.random() * (1 << 16)).toString(16),
    getObject = id => ({ [id]: { id } });

let object1 = getObject(getUUID()),
    object2 = getObject(getUUID());

console.log(object1);
console.log(object2);

Related