1

I am trying to get the first object within an object.

I have something like

var object = {
     task:{
       config:'auto',
       title :'test'
     },
     prop:'switch',
     time:'5min'
}

My problem is task object could be named differently. so it could be

var object = {
     task2:{
       config:'manual',
       title :'test2'
     },
     prop:'switch',
     time:'5min'
}

I can't use object.task1.config because task name could changed. The task object will always be the first object though.

I want to get the task object no matter what name it has. How do I accomplish that? Thanks!

4

2 回答 2

2

To get the first property value of an object in modern browsers you could use the Object.keys method:

var myObject = {
    whoTheHellKnows: 'foo',
    notUsed: 'whatever'
};

var firstProperty = myObject[Object.keys(myObject)[0]];

Working example

Edit: if you do not trust the ordering of the properties (which you should not) AND the task object is the only nested object in your objects, you can rely on type interrogation to find it:

var myObject = {
    task123215452: { dahKey: 'foo' },
    notUsed: 'whatever',
    somethingElse: 42
};

var taskObject;

for (var key in myObject) { 
    if (typeof myObject[key] === 'object' && !(myObject[key] instanceof Array)) {
        taskObject = myObject[key];
        break;
    }
}

Working example

于 2013-11-13T20:43:29.157 回答
2

If you need to access the first key and you don't know the key name, you should really be using an array instead of an object. Objects don't have the concept of a "first" key.

If that's not an option, you're left with for..in or Object.keys, which may fail on some JavaScript implementations because the language specification does not enforce the order of object key enumerations. However, in practice, it will work on current browsers, as they all iterate the keys in the order they were declaredcitation needed thanks to jbabey.

于 2013-11-13T20:48:32.887 回答