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/app/app.component.ts
CodePudding user response:
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.