我有这样的代码:
var data = [
{
first_name: "Apurv",
date: "2018-01-22",
is_present: "1",
},
{
first_name: "Lucky",
date: "2018-01-22",
is_present: "0",
},
{
first_name: "Apurv",
date: "2018-01-20",
is_present: "0",
},
{
first_name: "Lucky",
date: "2018-01-20",
is_present: "1",
}
];
var groupByName = {};
data.forEach(function (a) {
groupByName [a.first_name] = groupByName [a.first_name] || [];
groupByName [a.first_name].push({ date: a.date, is_present: a.is_present });
});
console.log(groupByName);
我尝试使groupByName
变量的局部变量成为全局变量,以便在Angular 5上使用* ngIf进行操作,每个人都可以清除它,还是有另一种方法可以解决此问题?我会先谢谢你的!
答案 0 :(得分:2)
您应该将其作为组件的属性:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-mycomponent',
template: '<some html here>',
})
export class MyComponent implements OnInit{
public data:any[];
public groupByName:any;
ngOnInit() {
this.data = [
{
first_name: "Apurv",
date: "2018-01-22",
is_present: "1",
},
{
first_name: "Lucky",
date: "2018-01-22",
is_present: "0",
},
{
first_name: "Apurv",
date: "2018-01-20",
is_present: "0",
},
{
first_name: "Lucky",
date: "2018-01-20",
is_present: "1",
}
];
this.groupByName = {};
this.data.forEach(function (a) {
this.groupByName[a.first_name] = this.groupByName [a.first_name] || [];
this.groupByName[a.first_name].push({ date: a.date, is_present: a.is_present });
});
}
}