Reputation: 810
I need to merge/push data into object.
My code is:
export class HeaderComponent implements OnInit {
site_heading = "Business Casual";
menubar = [];
isLogged = true;
constructor() {
this.menubar = [{
'link': 'home',
'name': 'Home'
}, {
'link': 'about',
'name': 'About'
}, {
'link': 'store',
'name': 'Store'
}, {
'link': 'products',
'name': 'Products'
}];
let userMenu = [{
'link': 'myprofile',
'name': 'My Profile'
}, {
'link': 'logout',
'name': 'LogOut'
}];
userMenu.forEach(function(value) {
this.menubar.push(value);
});
}
ngOnInit() {}
}
Its showing error:
ERROR TypeError: Cannot read property 'menubar' of undefined
Upvotes: 1
Views: 42
Reputation: 222682
Use an arrow function,
Arrow function is anonymous and doesn't bind its own this. Hence, this is this of current context.
userMenu.forEach((value) => {
this.menubar.push(value);
});
Upvotes: 0
Reputation: 476
This should work:
let self = this
userMenu.forEach(function (value) {
self.menubar.push(value);
});
Or lambda expressions (arrow functions)
Upvotes: 2
Reputation: 8851
You need to use an arrow funciton instead of a regular function, to ensure this
context is OK:
...
userMenu.forEach((value) => {
this.menubar.push(value);
});
...
Upvotes: 3