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

1
  • 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, {...}]. Commented Jul 12, 2022 at 9:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Can you update in the stackblitz?
test.reverse()
I'm sorry, but you posted a question and I answered it, and even updated the StackBlitz. I don't really have the time to to do basic JavaScript/TypeScript/Angular tutoring. I suggest you either find a tutor, or start with a basic JavaScript course and work your way up from there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.