What is the best way to get/set an objects deep property in Javascript?

前端 未结 2 516
孤街浪徒
孤街浪徒 2021-01-24 18:00

It is notoriously annoying to get a deeper property from an object. If the parent does not exist, you get an error. So you need to stop getting to the property when a parent doe

相关标签:
2条回答
  • 2021-01-24 18:31

    Instead of try..catch, just test for the property:

    function getProp(path, parent) {
        path = path.split('.');
    
        for (var k=0, kLen=path.length; k<kLen; k++) {
    
            if (parent.hasOwnProperty(path[k])) {
                parent = parent[path[k]];
    
            } else {
              return; // undefined? null? error?
            }
        }
        return parent;
    }
    
    var obj = {a: {b: {c: 'C', d:'D'}}};
    
    console.log(
      getProp('a.b.d', obj)  // D
    );      
    
    0 讨论(0)
  • 2021-01-24 18:51

    Builtin ways, no. If you're in Node.js platform you can try some package like dotty.

    Anyway, the way I think you could do it is somewhat like this (I haven't tested it! But I think it could work):

    key.split( "." ).reduce(function( memo, part ) {
       if ( typeof memo !== "object" || memo[ part ] === undefined ) {
          return;
       }
    
       return memo[ part ];
    }, obj );
    
    0 讨论(0)
提交回复
热议问题