Access JSON data with string path?

后端 未结 4 1273
温柔的废话
温柔的废话 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.

    0 讨论(0)
  • 2021-01-15 04:25

    Use Array#reduce() method

    var give = 'i.want.it';
    
    var obj = {
      i: {
        want: {
          it: 'Oh I know you do...'
        }
      }
    };
    
    
    var res = give.split('.').reduce(function(o, k) {
      return o && o[k];
    }, obj);
    
    console.log(res);

    0 讨论(0)
  • 2021-01-15 04:27

    make it

    var obj = {
        i: {
            want: {
                it: 'Oh I know you do...'
            }
        }
    };
    //var result = JSON.parse(JSON.stringify(obj)); //cloning the existing obj
    var result = obj; //cloning the existing obj
    var give = 'i.want.it';
    
    //now split the give and iterate through keys
    give.split(".").forEach(function(key){
      result = result[key];
    });
    console.log(result);

    0 讨论(0)
  • 2021-01-15 04:31

    You can use eval()

    var obj = {"a": { "b": { "c": 3}}}; writeln(eval('obj.a.b.c') + 2);

    This will output 5.

    JavaScript is weakly typed and thus it's evaluation function executes a statement as well as evaluating an expression.

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