我有一个项目数组,如: -
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' }
];
一个标题数组是: -
this.headers = [
{ name: 'id', show: true },
{ name: 'name', show: true },
{ name: 'address', show: false }
];
我正在做类似的事情: -
let obj = this.headers[0].name; // this is coming as 'id'
console.log(this.itemList[0].id) // this showing as 1
这是正确的,但当我这样做时: -
console.log(this.itemList[0].obj) // it says undefined, why?
有什么方法可以获得这个价值吗? 感谢
答案 0 :(得分:3)
你应该这样做:
this.itemList[0][obj]
原因:
为什么这不起作用?
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
但是:
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']