Access JSON data with string path?

后端 未结 4 1274
温柔的废话
温柔的废话 2021-01-15 03:47
var give = \'i.want.it\';

var obj = {
    i: {
        want: {
            it: \'Oh I know you do...\'
        }
    }
};

console.log(obj[give]); // \'Oh I know yo         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-15 04:20

    This will work :

    var give = 'i.want.it';
    
    var obj = {
      i: {
        want: {
          it: 'Oh I know you do...'
        }
      }
    };
    
    console.log( eval("obj."+give));
    

    Live DEMO JSFiddle

    This is a really easy way to do it, but not safe, i don't advise you to use it for professional use. Use previous answer they looks good.

提交回复
热议问题