1

I need to access object properties with dynamic keys which has persistent structure but different keys, like on one occasion it could be:

 var ty_tabs=[{ "key1" :[{ "d1" : "v1", "d2" : "v2", "d3" : "v3" }], "key2" :[{ "d1" : "v1", "d2" : "v2", "d3" : "v3" }] }] 

and on another one:

 var ty_tabs=[{ "key3" :[{ "d1" : "v1", "d2" : "v2", "d3" : "v3" }], "key4" :[{ "d1" : "v1", "d2" : "v2", "d3" : "v3" }] }] 

How do I adopt my code:

var b,a,d1,d2,d3; for (b = 0 , a = ty_tabs.length; b < a ; ++b){ d1 = ty_tabs[b].key1[0].d1; d2 = ty_tabs[b].key1[0].d2; d3 = ty_tabs[b].key1[0].d3; } 

To access properties with varying keys:

 d1 = ty_tabs[b].?[0].d1; d2 = ty_tabs[b].?[0].d2; d3 = ty_tabs[b].?[0].d3; 
1
  • I have in JSON data ,array value as object as name array; this name array is dynamic value and this value have dynamic value. Commented Feb 13, 2014 at 8:57

1 Answer 1

0

If you don't know about the keys of an object, but need all keys present within an it, you can use Object.keys():

var b,a,d1,d2,d3, i, keys; for (b = 0 , a = ty_tabs.length; b < a ; ++b){ keys = Object.keys( ty_tabs[b] ); for( i=0; i<keys.length; i++ ) { d1 = ty_tabs[b][ keys[i] ][0].d1; d2 = ty_tabs[b][ keys[i] ][0].d2; d3 = ty_tabs[b][ keys[i] ][0].d3; } } 

Object.keys() is rather well supported. For older versions of IE, you can use the polyfill provided at MDN

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.