Using variables with nested Javascript object

前端 未结 5 1699
甜味超标
甜味超标 2020-12-25 15:08

Suppose I have this:

var a = { A : { AA : 1 }, B : 2 };

Is there a way for me to create a variable that could allow me to reference either

5条回答
  •  萌比男神i
    2020-12-25 15:45

    Actually no, because js object are seen as property bags and doing a[X] is for accessing first level properties only...

    But you could wrap the logic a['A']['AA']; // 1 in a function that does the same, like this

    //WARN... no undefined check here => todo !
    function _(o, path) {
      var tmp = o
      for (var i=0 ; i < path.length ; i++) {
        tmp = tmp[path[i]]
      }
      return tmp
    }
    
    var r = _(a, ['A', 'AA'])
    

    This is pretty much the same as other answers, but the difference is when dummy boy create object property name containing dots... Like var a = {"a.a" : 3 } is valid.

    Now, such problem would occurs maybe more often now with the help of IndexedDB to store anything locally...

提交回复
热议问题