Home > OS >  Change Object Index
Change Object Index

Time:09-24

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

CodePudding user response:

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

  • Related