1

I am trying to create a new array from the existing json data but i am not able to add new key in the json data. If you check my code you can understand. If anyone knows please help to find the solution.

app.comppnent.ts:

ngOnInit(): void {
        this.httpClient.get('../assets/data.json').subscribe((data) => {
        console.log(data);

        this.allData.push(data);

        for (var j = 0; j <= this.allData.length; j++) {
            this.groupData = { item: this.allData[j], checked: true };
        }
        });
    }

      console.log(this.groupData);
  }

Finally the console.log(this.groupData) should be like

   [  
    {
      item: "Bus",
      checked: true
    },
    {
      item: "Car",
      checked: true
    },
    {
      item: "Auto",
      checked: true
    } 

   ];



     

Demo: https://stackblitz.com/edit/angular-ivy-iz5khq?file=src%2Fapp%2Fapp.component.ts

EMahan K
  • 417
  • 1
  • 19
  • You are resetting your group data on each loop iteration as an object when its an array. you should say this.groupData.push(...) or if you want to create a new array [...this.groupData, {...}]. – Dean Jul 12 '22 at 09:09

1 Answers1

1

Since your JSON file contains a string array, it's just a matter of typing your expected response and correctly mapping it:

ngOnInit(): void {
  this.httpClient.get<string[]>('../assets/data.json').subscribe((data) => {
    this.allData.push(...data); // do you actually need this?
    this.groupData = data.map((item) => ({item, checked: true}));
  });
}

Note, that if you want to log your groupData you need to do so inside the subscribe() block.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156