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

前端 未结 2 523
孤街浪徒
孤街浪徒 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: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 );
    

提交回复
热议问题