简体   繁体   中英

How can I get a value from a javascript object when I don't know the property name

I have an object var obj = {id: value}

In my html, I want to show the id and the value.

I'm using angularjs.

Please: I don't want a solution with ng-repeat, because I get only one element in this object

Thank you

On a modern browser, you can get a list of an object's "own" property names (not ones from its prototype) via Object.keys . If the object has only one property, you'll get back only one name:

var name = Object.keys(obj)[0]; // [0] = get the first (only)

On older browsers, you can via a for-in loop: (Or, you can get a "shim" or "polyfill" for Object.keys , which would use one under the covers)

var name, n;
for (n in obj) {
    if (obj.hasOwnProperty(n)) {
        name = n;
        break;
    }
}

Once you know the name, you can use that to get the value:

var value = obj[name];

Side note: It's generally best to design objects so that the property names are consistent, and the values vary. So for instance, rather than {id: value} where both id and value are variable, perhaps {id: "the ID", value: "the value"} where the property names are consistent and the values vary. Then you could just use obj.id and obj.value .

I am not really sure what your question is. You have an object named obj and which has a property named id.

Do you want to show the value of the property named id? If so, something like this:

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app ng-init="obj = {id: 'foo'}"> Object id: {{obj.id}} </div> 

Or is a situation where the object is more like a dictionary, where the property is a variable key?

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app ng-init="obj = {bar: 'foo'}; id = 'bar'"> Object {{id}}: {{obj[id]}} </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM