How to to get the key of a key/value javascript object?

0 votes

I have a JS object like:

var foo = { 'bar' : 'baz' }

If I know that foo has that basic key/value structure, but don't know the name of the key, what's the easiest way to get it? for ... in? $.each()? 

Oct 9 in Java-Script by kartik
• 35,780 points
49 views

1 answer to this question.

0 votes

Hello @kartik,

You would iterate inside the object with a for loop:

for(var i in foo){
  alert(i); // alerts key
  alert(foo[i]); //alerts key's value
}

Or

Object.keys(foo)
  .forEach(function eachKey(key) { 
    alert(key); // alerts key 
    alert(foo[key]); // alerts value
  });

Hope it helps!!

Thank you!!

answered Oct 9 by Niroj
• 78,000 points

Related Questions In Java-Script

0 votes
1 answer

How to convert an Object {} to an Array [] of key-value pairs in JavaScript?

Hello @kartik, You can use Object.keys() and map() to do this var obj ...READ MORE

answered Sep 4 in Java-Script by Niroj
• 78,000 points
159 views
0 votes
1 answer

How to get the file name from a full path using JavaScript?

Hello @kartik, Use this: var filename = fullPath.replace(/^.*[\\\/]/, '') This ...READ MORE

answered Sep 2 in Java-Script by Niroj
• 78,000 points
95 views
0 votes
1 answer

How to Change the selected value of a drop-down list with jQuery?

Hello @kartik, With hidden field you need to ...READ MORE

answered Sep 9 in Java-Script by Niroj
• 78,000 points
42 views
0 votes
1 answer

How to get the value of an input field using ReactJS?

Hello @kartik, Managed to get the input field ...READ MORE

answered Oct 8 in Java-Script by Niroj
• 78,000 points
84 views
0 votes
1 answer

jQuery AJAX fires error callback on window unload - how do I filter out unload and only catch real errors?

Hello, In the error callback or $.ajax you have three ...READ MORE

answered Apr 27 in Java-Script by Niroj
• 78,000 points
448 views
0 votes
1 answer

How do I pass command line arguments to a Node.js program?

Hello @kartik, If your script is called myScript.js ...READ MORE

answered May 5 in Java-Script by Niroj
• 78,000 points
696 views
0 votes
1 answer

Error:Issue when trying to use IN() in wordpress database

Hello @kartik, Try this code : // Create an ...READ MORE

answered May 8 in PHP by Niroj
• 78,000 points
91 views
+2 votes
1 answer

How do I debug Node.js applications?

Hello @kartik, Use node-inspector  from any browser supporting WebSocket. Breakpoints, ...READ MORE

answered Jul 8 in Node-js by Niroj
• 78,000 points
87 views
0 votes
1 answer

How to get the size of a JavaScript object?

Hello @kartik, Use this code: function roughSizeOfObject( object ) ...READ MORE

answered Sep 23 in Java-Script by Niroj
• 78,000 points
31 views
0 votes
1 answer

How to list the properties of a JavaScript object?

Hii @kartik, Use Reflect.ownKeys(): var obj = {a: 1, b: ...READ MORE

answered Jun 8 in Java-Script by Niroj
• 78,000 points
114 views