1

I have a JSON Object which is dynamically created based on user interaction, the dynamic key will change every time

example JSON

{ "normalkey": "John Smith", "dynamickey ": "testing" } 

is there any way to assign the dynamic key name without knowing the key name for example.

$.ajax({ type: "POST", url: ROOT+"controlpanel/menuBuilder", data: "clicked="+menu, dataType:"json", success: function(data) { $('#foo').html(data.normalKey); $('#bar').html(data.dynamicKey); } 
3

2 Answers 2

2

when space come in name then use [] Bracket notation pattern

success: function(data) { $('#foo').html(data["normal key"]); $('#bar').html(data["dynamic key"]); } 

updated to get key use jQuery.each

$.each(data, function(key, item){ console.log(key); // here you get the key names }); 
Sign up to request clarification or add additional context in comments.

2 Comments

[] is called Bracket notation
Hi, its not the space thats the issue the dynamic key will be different every time, so next time it could be dynamic key 2 for example. My question is how do i access the key without knowing its name?
1

As this is an javascript object you can use jQuery's $.each() method to get the key names:

success: function(data) { $.each(data, function(key, item){ console.log(key); // this gets you the key names }); } 

Demo @ Fiddle


As per your comment

how would i assign key 2 to a variable without using its name?

var o = { "normalkey": "John Smith", "dynamickey ": "testing" }; var a = []; // declare an empty array. $.each(o, function(key, item){ a.push(key); // push the keys in it. }); var dynkey = a.pop(); // .pop() gets you the dynamickey here as // this is the last item in the array. console.log(dynkey); // this logs = dynamickey 

Another Demo @ Fiddle


Description about .pop() @ MDN Docs:

The pop method removes the last element from an array and returns that value to the caller.


So with your last comment:

success: function(data) { var a = []; $.each(data, function(key, item){ a.push(key); // this gets you the key names }); var dynkey = a.pop(); $('#container').html(data[dynkey]); // <----here you have to do this. } 

5 Comments

that works i get normalKey dynamicKey how would i assign key 2 to a variable without using its name?
@user3524311 see the updated answer with fiddle link, readout the comments in the updated answer.
one last question, if i then wanted to use the dynkey could i do it like this, $('#container').html(data.dynkey);
@user3524311 Well in short i would say no. you cannot get it that way.
You can do this: $('#container').html(data[dynkey]);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.