3

I have this object:

var sub = {
    0:  [""],
    21: ["Look, here, are three little stuff,","ready to sing for this crowd"],
    28: ["Listen up, 'cause here's our story","I'm gonna sing it very LOUUU..."],
    36: [""],
    45: ["VERY LOUUU..."],
    48: [""],
    61: ["When you're a younger stuff","and your stuff is very bare"],
    68: ["Feels like the sun will never come","when your stuff's not there"],
    74: ["So the three of us will fight the fight","there is nothing that we fear"],
    80: ["We'll have to figure out what we'll do next","till our stuff is here!"],
    87: ["We are the guys","on a quest to find out who we are"],
    94: ["And we will never stop the journey","not until we have our stuff"],
    101:[""],
    106:["(stuff...)"],
}
//I like stuff.

And I would like to get all of the variable names into an array, like so:

variables == [0, 21, 28, 36, 45, 48, 61, 68, 74, 80, 87, 94, 101, 106, 109];

Is there a built in function for this, or is it possible to iterate over JSON object variables?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
SeinopSys
  • 8,787
  • 10
  • 62
  • 110
  • This is a JavaScript object, not a JSON object! Please read [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). – Felix Kling Feb 22 '13 at 19:32
  • Objects have *properties*, not variables. What you are looking for is the *names* of the properties. –  Feb 22 '13 at 19:35
  • Following the solution in the linked question will give you an array of strings though. If you want to convert them to numbers, have a look at http://stackoverflow.com/questions/2130454/javascript-to-convert-string-to-number. – Felix Kling Feb 22 '13 at 19:36

2 Answers2

6

Most browsers have this method built right into the Object prototype.

You can use

var variables = Object.keys(sub); //returns an array with all the object keys

Hope that helps!

KDV
  • 730
  • 1
  • 6
  • 12
1
var variables = [];
for (var i in sub) {
 if (sub.hasOwnProperty(i)){
  variables.push(+i);
 }
}

This is a manual solution. I recommend you using Underscore.js for problems like this. There is a good _.keys method in Underscore.

Mohsen
  • 64,437
  • 34
  • 159
  • 186