Sandeep Thomas
Sandeep Thomas

Reputation: 4759

Finding an item in a JSON object array with some values and replace if existing

I have an array like this which is ofcourse dynamic and each of the element get pushed when clicking an add button next to few form fields

[{"EbudgetId":0,"CrId":0,"TypeId":"8","TypeName":"AUGMENT_STAFF","Year":2020,"Cost":456},
{"EbudgetId":0,"CrId":0,"TypeId":"8","TypeName":"AUGMENT_STAFF","Year":2020,"Cost":456},
{"EbudgetId":0,"CrId":0,"TypeId":"8","TypeName":"AUGMENT_STAFF","Year":2020,"Cost":456},
{"EbudgetId":0,"CrId":0,"TypeId":"8","TypeName":"AUGMENT_STAFF","Year":2021,"Cost":657}]

What my requirement is if there an Item which of a specific type and year already exists, then it should add with its value rather than pushing into the array.

With that intention I did like this but it doest work

  addExternalBudget() {
    
    let typeId:Number  = this.selectedExternalBudget.TypeId;
    let yr:number=this.selectedExternalBudget.Year;
    
    if(typeId==0 || yr==0) return false;

    let ebCopy: ExternalBudget = Object.assign({}, this.selectedExternalBudget);

    
    let existingBudget:ExternalBudget=this.myChangeRequest.NewExternalBudget.find(x=>{x.TypeId===typeId;x.Year==yr});
    if(existingBudget=== undefined){
      this.myChangeRequest.NewExternalBudget.push(ebCopy);
    }
    else
    {
      existingBudget.Cost=this.selectedExternalBudget.Cost+existingBudget.Cost;
    }
    
  }

here even when the item already exists with given typeid and year, it getting added as a new item into the array.

What I did wrong here?

I am working in Angular 9

Upvotes: 0

Views: 91

Answers (2)

ng-hobby
ng-hobby

Reputation: 2199

The problem is your find. You can use filter like this to get the matched items:

let foundItems = this.myChangeRequest.NewExternalBudget.filter( _ => (_.TypeId == typeId && _.Year == yr))

So, here you get an array of matched object that if its length > 0 you got some answers. So keep processing on foundItems .

Upvotes: 1

Akash
Akash

Reputation: 4612

Below is how your function addExternalBudget should look like. Your find method is incorrect, inner expression should not have curly braces. If it has curly braces, you will have to return the value explicitly -

addExternalBudget() {
    
    let typeId:Number  = this.selectedExternalBudget.TypeId;
    let yr:number=this.selectedExternalBudget.Year;
    
    if(typeId==0 || yr==0) return false;

    let ebCopy: ExternalBudget = Object.assign({}, this.selectedExternalBudget);

    
    let existingBudget:ExternalBudget=this.myChangeRequest.NewExternalBudget.find(x=> x.TypeId===typeId && x.Year==yr);
    if(!existingBudget){
      this.myChangeRequest.NewExternalBudget.push(ebCopy);
    }
    else
    {
      existingBudget.Cost=this.selectedExternalBudget.Cost+existingBudget.Cost;
    }
    
  }

Upvotes: 1

Related Questions