javascript - no se puede acceder a la propiedad de un objeto creado dinámicamente de un array en angularjs2+
Tengo un arreglo de elementos como :-
this.itemList = [
{ id: 1, name: 'a', address: 'as dasf a' },
{ id: 2, name: 'b', address: 'as dasf a' },
{ id: 3, name: 'c', address: 'as dasf a' }
];
un arreglo de encabezados es :-
this.headers = [
{ name: 'id', show: true },
{ name: 'name', show: true },
{ name: 'address', show: false }
];
Estoy haciendo algo como :-
let obj = this.headers[0].name; // this is coming as 'id'
console.log(this.itemList[0].id) // this showing as 1
esto es correcto, pero cuando estoy haciendo :-
console.log(this.itemList[0].obj) // it says undefined, why?
¿Hay alguna manera de que pueda obtener ese valor? Gracias
Respuesta #1
Deberías hacerlo así:
this.itemList[0][obj]
Razón :
¿Por qué esto no está funcionando?
this.itemList[0].obj
// this will not work coz it will try to find 'obj' as key in itemList[0]
// so it will return undefined
Pero esto :
this.itemList[0][obj]
// But in this one obj considered as varible and replace with its value
// so it will become this.itemList[0].id / this.itemList[0]['id']
