[removed] Getting a Single Property Name

前端 未结 5 1661
耶瑟儿~
耶瑟儿~ 2020-12-19 20:51

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 prope

相关标签:
5条回答
  • 2020-12-19 21:05

    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]

    0 讨论(0)
  • 2020-12-19 21:06

    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

    0 讨论(0)
  • 2020-12-19 21:11

    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 讨论(0)
  • 2020-12-19 21:25

    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;
    };
    
    0 讨论(0)
  • 2020-12-19 21:26

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题