Home > Mobile >  Replacement in a json array - Angular
Replacement in a json array - Angular

Time:06-19

I am trying to replace an object in my json web server array : If an object with a similar id is already in the json array.

This is my json array :

{
  "history": [
    {
      "id": 4,
      "SNS": "BockeSinoJutsu-SNS",
      "title": "BockeSinoJutsu-title",
      "DMC": "BockeSinoJutsu-DMC",
      "date": "June 15 2022"
    },
    {
      "id": 1,
      "SNS": "Rasengan-SNS",
      "title": "Rasengan-title",
      "DMC": "Rasengan-DMC",
      "date": "2022-06-18T17:43:59.708Z"
    }
  ]
}

And this is the json file I am comparing it to :

{
  "content":[
      {
        "id":1,
        "SNS":"Rasengan-SNS",
        "title":"Rasengan-title",
        "DMC":"Rasengan-DMC"
      },
      {
        "id":2,
        "SNS":"Mangekyu-SNS",
        "title":"Mangekyu-title",
        "DMC":"Mangekyu-DMC"
      },
      {
        "id":3,
        "SNS":"Chidori-SNS",
        "title":"Chidori-title",
        "DMC":"Chidori-DMC"
      }
  ]
}

This is what I have tried :

onAddHistory(history:History){
    history.date = new Date();
    console.log(history.SNS);
    this.historyService.getHistory().subscribe(
      (response:History[])=>{
        this.ExistingHistory=response.filter(x => x.id === history.id);
        console.log(this.ExistingHistory);
        if(this.ExistingHistory.length !== 0){
          this.onDeleteHistory(this.ExistingHistory.id);
          this.historyService.addHistory(history).subscribe(
            ()=>{console.log("Success !");
            this.Histories$=this.historyService.getHistory();},
            ()=>{console.log("error")}
          );
        }else{
          this.historyService.addHistory(history).subscribe(
            ()=>{console.log("Success !");
            this.Histories$=this.historyService.getHistory();},
            ()=>{console.log("error")}
          );
      }
    }
    );
    
    }

But I get the following error, saying that it cannot read id of undefined :

Error

The error basically says that ExistingHistory.id is undefined

CodePudding user response:

JavaScript's Array.filter() returns a filtered array. You can't access this.ExistingHistory.id because this.ExistingHistory is an array, you would have to access it like so: this.ExistingHistory[0].id

If you want to get one value only then you should use Array.find():

this.ExistingHistory = response.find(x => x.id === history.id);

If there is a chance there is more than one duplicate, then you should use a .forEach loop:

this.ExistingHistory.forEach((x) => {
   this.onDeleteHistory(x.id);
}

Do be warned however that you have a ton of nested subscriptions in that method, which is generally considered bad practice. I advise you to look into RXJS

  • Related