How to use an array of keys to fetch the value from a Javascript object

前端 未结 3 1338
春和景丽
春和景丽 2020-12-12 02:53

If there is a Javascript object with multiple levels, as in:

myObject = {
        a: 12,
        obj11: {
                obj111: \'John\',
                b         


        
3条回答
  •  不知归路
    2020-12-12 03:41

    To increment the discussion, if you're using lodash you can also use the function _.get to get the value like this:

    _.get(myObject, ['obj111', 'obj1111'])
    //returns 'John'
    

    If you object has properties with array values you can also get by indexes

    var obj = {
            a: 1,
            b:[{
               d:4,
               c:8
            }]
    
    _.get(obj, ['b','0','d'])
    //returns 4
    

    Source: https://lodash.com/docs/4.17.4#get

提交回复
热议问题