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

前端 未结 3 1335
春和景丽
春和景丽 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

    0 讨论(0)
  • 2020-12-12 03:46

    You could reduce the array with the keys and take an object as default value.

    function getValue(object, path) {
        return path.reduce(function (r, k) {
            return (r || {})[k];
        }, object);
    }
    
    var object = { a: 12, obj11: { obj111: 'John', b: 13, obj1111: { a: 15, b: 35 }, obj21: { a: 15, b: 16 } } };
    
    console.log(getValue(object, ['obj11', 'b']));
    console.log(getValue(object, ['obj11', 'obj1111', 'a']));
    console.log(getValue(object, ['obj11', 'obj21']));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
  • 2020-12-12 03:46

    You can do this with a reduce() one-liner. Of course if you want to wrap it in a function, you can do that too.

    var myObject = {
        a: 12,
       obj11: {
               obj111: 'John',
               b:13,
               obj1111: { a:15,
                          b: 35 }
               },
       obj21: {
               a:15,
               b:16 }
    }
    
    var arr =   ['obj11','b']
    var val = arr.reduce((acc,curr) => acc[curr], myObject)
    console.log(val)
    
    var arr =   ['obj11','obj1111', 'b']
    var val = arr.reduce((acc,curr) => acc[curr], myObject)
    console.log(val)

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