1
var obj = {
   skill:{
      eat:true,
      walk:true
   },
   address:{
      home:"where",
      company:"where"
   }
};

I can get one item by:

tester.activate(obj[skill]);

How can I get all the items?

1
  • 3
    Your question is not clear at all. Commented Jan 31, 2011 at 17:14

2 Answers 2

5

You can iterate through the properties of an object with for ... in:

for (var k in obj) {
  if (obj.hasOwnProperty(k)) {
    var value = obj[k];
    alert("property name is " + k + " value is " + value);
  }
}

The call to the "hasOwnProperty" function is there to keep this code from iterating through properties present on "obj" that are actually inherited from the Object prototype. Sometimes you might want to include those, but in this case it's safe to filter them out (I think). (And @sdleihssirhc points out that if you want to be really sure, you can use Object.prototype.hasOwnProperty.call(obj, k) )

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

5 Comments

Let's see if your guess at the question paid off. (Or perhaps the question was clear to you and just not to me?)
@Phrogz my fingers are crossed - I agree that the question was completely vague.
@Phrogz the question was pretty unclear. I interpretted it differently aswell.
Obligatory note about using Object.prototype.hasOwnProperty.call for the sufficiently paranoid.
Good info for a very vague question FTW?!?
1

If you need the skill you can get

obj.skill

If you need the address you can get

obj.address

or if you wanted to get the individual data:

var eat = obj.skill.eat;
var company = obj.address.company;

If you want all the items you can iterate over the structure and push all the items to an array

function pushObjToArray(obj, array) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
             if (obj[key] instanceof Array) {
                  pushObjToArray(obj[key], array);
             } else if (obj[key] instanceof Object) {
                  pushObjToArray(obj[key], array);
             } else {
                  array.push(obj[key]);
             }
        }
    }
    return array;
}

var array = [];
pushObjToArray(array, obj);

On second thought destroying the keys and pushing all data to an array is pretty useless.

What do you actaully want to do?

You might be looking for something like _.flatten

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.