简体   繁体   中英

How to push some arrays to the main array in angular 8

Hi i am working on Angular 7 and I have 3 main arrays fetching from API like mentioned in stackblitz

And now the 3 main arrays look like this.

 this.mainarr = [
      { id: 1, name: "Praveen", age: 3, color: 3 },
      { id: 2, name: "kumar", age: 2, color: 4 },
      { id: 3, name: "john", age: 4, color: 2 },
      { id: 4, name: "alex", age: 5, color: 1 },
      { id: 5, name: "profes", age: 3, color: 2 }
    ];

    this.agearr = [
      { id: 1, age: 22 },
      { id: 2, age: 24 },
      { id: 3, age: 33 },
      { id: 4, age: 12 },
      { id: 5, age: 26 }
    ];

    this.colorarr = [
      { id: 1, color: "black" },
      { id: 2, color: "paleblack" },
      { id: 3, color: "brown" },
      { id: 4, color: "white" },
      { id: 5, color: "greyish" }
    ];

So, in the mainarr i have ids and the agearr and colorarr id matched i need a different key value pair in mainarr and display that values.

so my expected result should be

[
      { id: 1, name: "Praveen", age: 3, color: 3,agename: 33,colorname: 'brown'},
      { id: 2, name: "kumar", age: 2, color: 4,agename: 24,colorname: 'white'},
      { id: 3, name: "john", age: 4, color: 2 agename: 12,colorname:'paleblack'},
      { id: 4, name: "alex", age: 5, color: 1 agename: 26,colorname:'black'},
      { id: 5, name: "profes", age: 3, color: 2 agename: 33,colorname:'paleblack'}
];

I am getting the desired result but only after page refresh how to do it any idea?TIA

Try like following:

  getFunction() {
     this.mainarr.map(x => {
        x["agename"] = this.agearr.find(y => y.id == x.age)["age"];
        x["colorname"] = this.colorarr.find(y => y.id == x.color)["color"];
     });
     console.log(this.mainarr);
  }

Working Stackbllitz Example: https://stackblitz.com/edit/angular-ivy-ve5cdp?file=src/app/app.component.ts

Here is the updated stackblitz

In the if block you were checking for the wrong property. Corrected it.

if (this.mainarr[i].age == this.agearr[j].id)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM