最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: Getting a Single Property Name - Stack Overflow

programmeradmin3浏览0评论

Given an object like this:

{ name: "joe" }

I want to get the value "name". I know I can use the for construct to iterate over the properties in an object, but the objects I'll be dealing with will always have a single key:value pair, and I won't 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 anyway to do this without iterating over the object? Also I'd like to do this in pure Javascript. No frameworks/libs involved.

Given an object like this:

{ name: "joe" }

I want to get the value "name". I know I can use the for construct to iterate over the properties in an object, but the objects I'll be dealing with will always have a single key:value pair, and I won't 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 anyway to do this without iterating over the object? Also I'd like to do this in pure Javascript. No frameworks/libs involved.

Share Improve this question asked Oct 20, 2010 at 22:04 mellowsoonmellowsoon 23.3k19 gold badges58 silver badges76 bronze badges 1
  • Maybe you should use an array instead a=["age",24"], and then you get the name with a[0] – some Commented Oct 20, 2010 at 22:08
Add a ment  | 

5 Answers 5

Reset to default 7

It is good practice to use .hasOwnProperty to ensure you aren't returning a property from the Object prototype:

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

This seems to be about the best you can get:

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

Nope, iteration is the only well-supported way to get the property name. So for...in time it is. Just hide it in a function and it'll look fine.

However, it might also be worth thinkin about whether you should be using a different kind of object for your purpose, say, {"property": "age", "value": 24}, or even ["age", 24]

You can iterate over the object's properties and simply return the first one.

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

Edit: oops, you wanted the property name, not the value

Why not iterate? It's just one step. I don't think you can get it in any other way. You can even break after the first step if it makes you feel better.

发布评论

评论列表(0)

  1. 暂无评论