Use Object.keys:
var foo = {
'alpha': 'puffin',
'beta': 'beagle'
};
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys you can steal
javascript - Get array of object's keys - Stack Overflow
Generate an Array of All Object Keys with Object.keys()
Object.keys
Should you build a hash table using an array or an object?
Videos
Use Object.keys:
var foo = {
'alpha': 'puffin',
'beta': 'beagle'
};
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys you can steal
You can use jQuery's $.map.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
return i;
});
Do you use Object.keys often?
Can you explain what's going on in this code what would be the key, index.
At first I was still thing they was object not arrays because that's what they looked like. I know the key was username1/2/3/ and the value is ben/kevin/deku but they don't have index and removing index from the parameters changed nothing, but arrays have index but not keys. from the cosole.log to get the key we console.log key, and to get the value its obj[key] but why?
I tried console.log(Object.keys(obj)) but that mad it more confusing because now the names(values) where gone and it was just an array of the username(keys)
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key, index) =>{
console.log(key, obj[key]);
})
// username1 ben
// username2 kevin
// username3 deku
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key) =>{
console.log(key, obj[key]);
})
// username1 ben
// username2 kevin
// username3 deku
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key, index) =>{
console.log(obj[key]);
})
// ben
// kevin
// deku
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key) =>{
console.log(key);
})
// username1
// username2
// username3