简体   繁体   English

动态访问数组对象

[英]Accesing array objects dynamically

I have below array and trying to access the array objects based on key dynamically but its not giving me the exact object details ,I am getting table1/table2 values dynamically and based on that i am trying to get the table details我有下面的数组并尝试根据键动态访问数组对象,但它没有给我确切的对象详细信息,我正在动态获取 table1/table2 值,并基于此我试图获取表详细信息

var arr = [{"table1":{"tablename":"table1","tablecolumns":"no","patternCheckStatus":"true","columns":[{"columnname":"DescriptionGovt","datatype":"AlphaNumeric","patternregex":"(lll);;;"},{"columnname":"GovtGrant","datatype":"Alphabetic","patternregex":"(lkkll)"}]}},{"table2":{"tablename":"table2","tablecolumns":"no","patternCheckStatus":"false","columns":[{"columnname":"DateItem","datatype":"LowerCase","patternregex":"(3rdtable)hhhh"}]}}]

var id = table1;
console.log("obj " + JSON.stringify(arr[0].id));

i am getting undefined in console and i change the id with actual key name i am getting the object details.. console.log("obj "+ JSON.stringify(arr[0].table1));我在控制台中未定义,我用实际的键名更改了 id 我正在获取对象详细信息.. console.log("obj "+ JSON.stringify(arr[0].table1));

尝试这个。

var id = 'table1'; console.log("obj " + JSON.stringify(arr[0][id]));

this will work ==>这会起作用==>

var id ="table1";
console.log(" obj = "+JSON.stringify(arr[0][id]));

or或者

console.log(" obj = "+arr[0].table1);

in the first example, you are treating your object as a json by stringify it & in the second we are using it as POJO.在第一个示例中,您通过字符串化将对象视为 json,而在第二个示例中,我们将其用作 POJO。

Instead of arr[0].id , use arr[0][id] .代替arr[0].id ,使用arr[0][id]

  • arr[0].id is equivalent to accessing the id field from the first element of the array arr arr[0].id相当于从数组arr的第一个元素访问 id 字段
  • arr[0][id] is equivalent to accessing the field ${id} (ie the field which has the key, value of the id variable) from the first element of the array arr arr[0][id]相当于从数组arr的第一个元素访问${id}字段(即具有id变量的键、值的字段)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM