Using variables with nested Javascript object

前端 未结 5 1706
甜味超标
甜味超标 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条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-25 15:46

    Since i also encounter this problem, i wrote also a one line util for this (ES6):

    const leaf = (obj, path) => (path.split('.').reduce((value,el) => value[el], obj))
    

    Example:

    const objSample = { owner: { name: 'Neo' } };
    const pathSample = 'owner.name';
    
    leaf(objSample, pathSample) //'Neo'
    

提交回复
热议问题