【问题标题】:How to push some arrays to the main array in angular 8如何以角度 8 将一些数组推送到主数组
【发布时间】:2021-05-31 14:38:48
【问题描述】:

您好,我正在处理 Angular 7,我有 3 个从 API 获取的主要数组,如 stackblitz 中提到的那样

现在 3 个主数组看起来像这样。

 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" }
    ];

所以,在mainarr 中,我有 id,agearrcolorarr id 匹配,我需要在 mainarr 中使用不同的键值对并显示该值。

所以我的预期结果应该是

[
      { 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'}
];

我得到了想要的结果,但只有在页面刷新之后怎么办?TIA

【问题讨论】:

  • 这可能不相关,但是您声明了两个不同的 Angular 版本,这令人困惑。我还认为标题具有误导性。您正在尝试基于 id 属性合并对象属性?

标签: javascript arrays angular angular7 angular8


【解决方案1】:

尝试如下:

  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);
  }

工作Stackbllitz 示例:https://stackblitz.com/edit/angular-ivy-ve5cdp?file=src/app/app.component.ts

【讨论】:

  • 您好,感谢您的回答,当我转到实际代码时,我得到的年龄名称是未定义的。
  • 年龄的关键是什么
【解决方案2】:

Here 是更新的堆栈闪电战

在 if 块中,您检查了错误的属性。更正了。

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

【讨论】:

  • 这里的问题是我得到的答案只是刷新页面所以任何其他方式来做到这一点。感谢您的回答。
  • 再次检查闪电战。 stackblitz.com/edit/angular-ivy-f4v3gl?file=src/app/…我不明白你刷新页面是什么意思。你能再解释一下吗?
  • 这看起来不错,但在我的项目中,在 ng serve 后记录没有显示,但在刷新记录后反映。
  • 这通常意味着更新对象后没有运行更改检测。如果不查看代码,就无法诊断问题。这是一个起点。您可以尝试在 Change Detection Ref 上调用 detectChanges。 indepth.dev/posts/1053/…
猜你喜欢
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 2020-12-25
  • 1970-01-01
相关资源
最近更新 更多