Reputation: 18097
If I have an object like:
var o = {a:1,b:2,c:3};
I want to get:
['a','b','c'];
I want to use for (var i in o)
because this will include properties from prototype chain. I could have used Object.keys(o)
if I didn't need properties from prototype chain.
I was thinking I could use some of Array.prototype.*
methods here. Like map
but this is too advance for me.
I can make a string from loop and do split. But is there more efficient and professional level of doing this?
Upvotes: 3
Views: 2232
Reputation: 3254
This is a solution that avoids the for...in
that you mentioned. However, I think the for...in
solution is much more elegant.
This will walk the prototype chain and return all properties as a recursive function. As well as remove all duplicates.
function getKeys(obj) {
var keys = Object.keys(obj);
var parent = Object.getPrototypeOf(obj);
if (!parent) {
return keys;
}
return keys.concat(getKeys(parent))
.filter(function (item, index, col) {
return col.indexOf(item) === index;
});
}
var a = { a: 1, b: 2 };
var b = Object.create(a);
b.a = 2;
b.c = 3;
var c = Object.create(b);
console.log(getKeys(c));
Upvotes: 0
Reputation: 1162
You can use the keys method in lodash, https://lodash.com/docs#keys
You could also use the following code
var arr = [];
var o = {a:1,b:2}
for(k in o) { arr.push(k); }
Here is another version which goes deep into the object
function getKeys(o) { var arr = []; for(k in o) { arr.push(k); if(typeof(o[k]) === 'object') { arr.push(getKeys(o[k])); }} return arr; }
If you have an object like {a:1,b:2, c: {d:1, e:2}} you would get the return as ['a','b','c',['d','e']]
A completely flat version would be this one
function getKeys(o) { var arr = []; for(k in o) { arr.push(k); if(typeof(o[k]) === 'object') { for(j of getKeys(o[k])){ arr.push(j); } }} return arr; }
Upvotes: 4
Reputation: 1939
If you have the following hash
var o = {a:1,b:2,c:3};
Create a new empty array for storing the keys
var array_keys = new Array();
Then use a for loop to push the keys into the array
for (var key in o) {
array_keys.push(key);
}
You can then run alert(array_keys)
Upvotes: 0