0

I'm hoping my question is using the correct terminology...

Can someone explain to me how I can perform the following:

If I have an array consisting of:

Object { id=1498, brandName="Booths", quality="Standard"} Object { id=1499, brandName="Booths", quality="Standard"}

How can I iterate throughout that array and return another array of distinct 'keys'?

Ultimately I want an array which would return something like:

[id,brandName,quality] (but the original array is going to return different keys at different times.

Have I made sense?

3
  • You may simply use for (var key in obj) { ... }. Or is there a problem? If so, show us your code. Commented Sep 21, 2012 at 10:45
  • No, have tried that, it just returns the first key, I need it pumped to an array with unique keys. Commented Sep 21, 2012 at 10:47
  • What defines unique? Comparing those objects? Commented Sep 21, 2012 at 10:48

2 Answers 2

3

You can use Object.keys:

var a1 = [{ id:1498, brandName:"Booths", quality:"Standard"}, 
          { id:1499, brandName:"Booths", quality:"Standard"}],
    a1Keys = a1.map(function(a){return Object.keys(a);});
//a1Keys now:
[['id','brandName','quality'],['id','brandName','quality']]

The keys method is described @MDN, including a shim for older browsers

Sign up to request clarification or add additional context in comments.

1 Comment

That's almost exactly what I want, returns the names exactly as wanted, just need to now return only one array of unique keys rather than 1500 of them. Thank you.
0
var a = {"a": 1, "b": "t" };
var keys = new Array();
for(var o in a){
    keys.push(o);
}
console.log(keys)

Comments

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.