首页 > 解决方案 > 如何在单击angular / javascript中的按钮时将数组的特定键值一一推送到其他数组中

问题描述

我有一个对象 marrayval 数组,我需要从该数组中获取“国家”的值,并且需要在每次单击后将所有元素一个一个地推入 arrayval。例如 - 第一次单击需要推 C1,然后下一个点击需要推动 c1,C2 然后 c1,c2,c3.. 直到结束。这是下面的代码https://stackblitz.com/edit/angular-cjzdqc?file=src%2Fapp%2Fapp.component.ts

app.component.html

    <div (click)="getArray()">Click</div>

app.component.ts

    import { Component,OnInit} from '@angular/core';
    
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'testapp';
      arrayval = [];
      userName:any;
      constructor() { }
      marrayval = [{"id":1,"country":"C1","count":2},{"id":2,"country":"C2","count":1},{"id":3,"country":"C3","count":1}];
     
      ngOnInit() {
     
      }
     
    getArray(){
     this.marrayval.forEach((element) => {
         console.log(element);
                 this.arrayval.push(element.country);    
             });
              console.log(this.arrayval);
      }
     
    }

标签: angular

解决方案


// click 1: [c1]
// click 2: [c1, c2]
// click 3: [c1, c2, c3]
// click 4: [c1, c2, c3]
// click 5: [c1, c2, c3]

this.arrayval =
   this.marrayval
  .filter((_, index) => index <= this.arrayval.length)
  .map(element => element.country);

推荐阅读