Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting JavaScript object key list

Tags:

javascript

I have a JavaScript object like

var obj = {    key1: 'value1',    key2: 'value2',    key3: 'value3',    key4: 'value4' } 

How can I get the length and list of keys in this object?

like image 998
user160820 Avatar asked Jun 18 '10 09:06

user160820


People also ask

How do I get a list of keys from an object?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.

How do you get the keys of an array of objects?

To convert an array's values to object keys:Declare a new variable and set it to an empty object. Use the forEach() method to iterate over the array. On each iteration, assign the array's element as a key in the object.

How do I get all the values of an object?

values() Method: The Object. values() method is used to return an array of the object's own enumerable property values. The array can be looped using a for-loop to get all the values of the object.


2 Answers

var obj = {     key1: 'value1',     key2: 'value2',     key3: 'value3',     key4: 'value4'  }  var keys = Object.keys(obj);  console.log('obj contains ' + keys.length + ' keys: '+  keys);

It's supported on most major browsers now.

like image 97
Anurag Avatar answered Sep 21 '22 12:09

Anurag


var obj = {   key1: 'value1',   key2: 'value2',   key3: 'value3',   key4: 'value4' }; var keys = [];  for (var k in obj) keys.push(k);  console.log("total " + keys.length + " keys: " + keys);
like image 44
zed_0xff Avatar answered Sep 23 '22 12:09

zed_0xff