0

I am trying to extract the names of all keys from an array of objects keeping time complexity as n(One loop only). The array is as below:

var addressArray = [{"city":"New York"},{"country":"USA"},{"zip": 45677}];

I want to extract the below:

var addressKeys = ["city", "country", "zip"].

I am able to do the same by first looping through the array and then using a key in obj loop but that doesn't loo good. Alternatives are most welcome.

2
  • addressArray is not an array, it is an object Commented Apr 17, 2015 at 6:24
  • Edited the array. It is an array of objects. Commented Apr 17, 2015 at 6:57

4 Answers 4

3

Use Object.keys to get the keys.

if (typeof Object.keys !== "function") {
    (function() {
        Object.keys = Object_keys;
        function Object_keys(objectToGet) {
            var keys = [], name;
            for (name in objectToGet) {
                if (objectToGet.hasOwnProperty(name)) {
                    keys.push(name);
                }
            }
            return keys;
        }
    })();
}
Sign up to request clarification or add additional context in comments.

Comments

3

From your definition addressArray is an object not an array.

You can use Object.keys() to get the keys array of an object.

var addressKeys = Object.keys(addressArray);

To support older browsers, which does not support Object.keys you can use a Polyfill

1 Comment

@ArunPJony, I think this approach is slower because it has to create instance of Object and do some OOP methods. Test at : jsperf.com/object-keys-vs-for-in
2

Use for-in loop to access each key-value pair and then push to new array: (Recommended)

for(var index in addressArray){
    addressKeys.push(index)
}

Another solution is:

var addressKeys = Object.keys(addressArray)

which is slower comparatively.

Comments

1

Note that I switched []'s with {}'s:

var addressObject = {"city":"New York", "country":"USA", "zip": 45677};

var keys = [];

for(var address in addressObject)
{
    keys.push(address);
}

console.log(keys);

2 Comments

If I had a single object I would not have asked the question.
@JyotirmoyPan Your example has problems then. You need to update it with an array of objects you want to get the keys of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.