I have a JavaScript object like
var obj = {
key1: \'value1\',
key2: \'value2\',
key3: \'value3\',
key4: \'value4\'
}
How can I
var keys = new Array();
for(var key in obj)
{
keys[keys.length] = key;
}
var keyLength = keys.length;
to access any value from the object, you can use obj[key];
Underscore.js makes the transformation pretty clean:
var keys = _.map(x, function(v, k) { return k; });
Edit: I missed that you can do this too:
var keys = _.keys(x);
if(props.userType){
var data = []
Object.keys(props.userType).map(i=>{
data.push(props.userType[i])
})
setService(data)
}
Using ES6,
you can use forEach
to iterate over the Keys of an Object.
To get all the keys you can use Object.keys
which returns all the keys in an Object
Object.keys(obj).forEach(function(keyValue, index, map) {
console.log(keyValue);
});
Short hand of the above snippet would be, which only takes one parameter
Object.keys(obj).forEach(function(keyValue) {
console.log(keyValue);
});
var obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4'
};
var keys = [];
for (var k in obj) keys.push(k);
alert("total " + keys.length + " keys: " + keys);