3

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
  }
}
2
  • 2
    Why wouldn't you store it in a temp var ? Commented Oct 22, 2018 at 11:34
  • @R.Duteil If I have to insert multiple objects into obj with different ID's that'd be tiring to write. Commented Oct 22, 2018 at 11:59

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

this would be the best way to to do it
2

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

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.