Javascript: getting a single property name

For an object like this:

{ name: "joe" }

I want to get the value "name". I know that I can use the for construct to iterate over the properties of an object, but the objects that I will deal with will always have one key pair: the value, and I will not know the name of the property. To further illustrate:

var a = { age: 24 };
console.log(myFunc(a)) // Displays "age"

var b = { job: "cook" };
console.log(myFunc(b)) // Displays "job"

Is there a way to do this without iterating over an object? I would also like to do this in pure Javascript. No frameworks / libs.

+3
source share
5 answers

It is recommended to use .hasOwnPropertyto ensure that you do not return a property from the object prototype:

function myFunc(obj) {
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) return prop;
    }
}
+6
source

This seems like the best you can get:

function myFunc(v) {
  for (var x in v) { return { prop: x, val: v[x] }; }
  return null;
};
+3

, . , for...in . , .

, , , , , {"property": "age", "value": 24} ["age", 24]

+2

.

function myFunc(obj) {
    for (var prop in obj) {
        return prop;
    }
}

: oops, ,

+2

? . , - . , .

+1

Source: https://habr.com/ru/post/1770624/


All Articles