Get value of first object property

前端 未结 2 1681
北恋
北恋 2021-01-05 02:23

I have a simple object that always has one key:value like var obj = {\'mykey\':\'myvalue\'}

What is the fastest way and elegant way to get

相关标签:
2条回答
  • 2021-01-05 02:32
    function firstProp(obj) {
        for(var key in obj)
            return obj[key]
    }
    
    0 讨论(0)
  • 2021-01-05 02:33
    var value = obj[Object.keys(obj)[0]];
    

    Object.keys is included in javascript 1.8.5. Please check the compatibility here http://kangax.github.io/es5-compat-table/#Object.keys

    Edit:

    This is also defined in javascript 1.8.5 only.

    var value = obj[Object.getOwnPropertyNames(obj)[0]];
    

    Reference:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FWorking_with_Objects#Enumerating_all_properties_of_an_object

    0 讨论(0)
提交回复
热议问题