Django
Django

Reputation: 64

Change Object Index

Is there way to change the index dynamically? or rebuild this object to where the 1 will be the Id of what ever object get passed into the function? Hope this makes sense.

export const createTree = (parentObj) => {

//keep in memory reference for later
const flatlist = { 1: parentObj }; <---- change the 1 based on parent.Id

...

}

My attempt thinking it would be easy as:

const flatlist = { parentObj.Id: parentObj };

Upvotes: 0

Views: 110

Answers (1)

Ori Drori
Ori Drori

Reputation: 193087

Use computed property names to create a key from an expression:

const createTree = (parentObj) => {
  const flatlist = { [parentObj.id]: parentObj };

  return flatlist;
}

console.log(createTree({ id: 1 }));

Upvotes: 1

Related Questions