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?
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.
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.
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.
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.
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);  If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With