Accessing a JavaScript's object property without knowing that property name

前端 未结 3 1300
北恋
北恋 2020-12-05 19:04

Situation

I have a JSON object which is returned. And Below is an example of one. The who in this particular example can change to what

相关标签:
3条回答
  • 2020-12-05 19:38

    You can also use the for in loop:

    data.forEach( function ( m ) {
    
      for ( var key in m ) {
    
        console.log( key ); // "who"
        console.log( m[key] ); // "Arthur"
    
      }
    
    });
    

    The above would also work for multiple key: value pairs in your object i.e:

    [ {"who":"Arthur","who":"Fred"} ]
    
    0 讨论(0)
  • 2020-12-05 19:48

    If you always expect these objects to have only one property, you could do something like this:

    var name, person;
    for (person in data) {
        for (name in data[person]) {
            console.log(data[person][name]);
        }
    }
    

    This would enumerate through each property of each person in the data. Because there is only one property per person (I assume), it will just enumerate that one property and stop, allowing you to use that property regardless of its name.

    0 讨论(0)
  • 2020-12-05 19:53

    Object.keys(m)[0] should return the first enumerable property name in the object m.

    So if m = {"who": "Arthur"}; then m[Object.keys(m)[0]] will be "Arthur".

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys


    Alternatively: Object.values(m)[0]. See Object.values

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