0

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

Django
  • 64
  • 6
  • 1
    Does this answer your question? [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – pilchard Sep 23 '21 at 22:03

1 Answers1

1

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 }));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209