josh_boaz
josh_boaz

Reputation: 2023

Issue constructing a tree using a tree

So I have this method which basically traverses through a tree and constructs another tree, basically a map method but for an array, but im facing issue that instead of constructing a tree properly all nodes except the first level are duplicated. Can anyone point out what im doing wrong here?

 convertToTree(arcm: any, tree: any) {
    let a = {
      text: arcm.name,
    };

    Object.assign(tree, a);
    if (arcm.parcmTreeMapping && arcm.parcmTreeMapping.length) {
      let arr = new Array<any>(arcm.parcmTreeMapping.length).fill(new Object());
      tree['children'] = arr;
      arcm.parcmTreeMapping.forEach((item, index) => {

        this.convertToTree(item, tree.children[index], descList)
      });
    }
    else{
      return;
    }
  }

Upvotes: 0

Views: 35

Answers (1)

Mark
Mark

Reputation: 92450

When you use fill() with new Array() it will first construct a single object and then fill the array with references to the same object. You end up with an array of references to one object:

let arr = new Array(5).fill(new Object())
// they're all the same object
console.log(arr[0] === arr[1])
console.log(arr[2] === arr[3])

// modify one modifies them all:
arr[0].name = "Mark"
console.log(arr[1], arr[2])

You might try to map() instead so you create a new object each time:

let arr =  Array(5).fill().map(() => new Object)
console.log(arr)
console.log(arr[0] === arr[1])

Upvotes: 1

Related Questions