angular - 如何在单击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);
}
}
解决方案
// 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);
推荐阅读
- firebase - 如何更改 React Native iOS 项目的 Firebase 通知帐户?
- gcc - -mfpu=fpv5-sp-d16 和 -mfpu=fpv5-d16 有什么区别?
- sql - 编译语句时出错:FAILED:SemanticException [错误 10128]:第 4:7 行尚不支持 UDAF 位置
- java - 查询结果为空时如何使用 NVL 从 GemFire 获取数据
- angular - AngularDart 依赖注入
- android - 使用Blue Stack作为模拟器时如何查看后台进程并登录android studio?
- angular - 无法在 Angular 6 TS 中访问 POST 服务
- javascript - 你如何使增量计数器更具可读性?
- reactjs - SCRIPT438:对象不支持属性或方法“setPrototypeOf”
- vim - 在 Vim 中替换整个字符串