3

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?

2
  • var a = []; for (var oe in o) { a.push(oe); } Commented Mar 6, 2015 at 17:53
  • @ZeRubeus: JSON.stringify doesn't include inherited properties. Commented Mar 6, 2015 at 18:17

3 Answers 3

4

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; }
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.