how would I go about accessing a deep value using a single variable in bracket notation?

前端 未结 3 1219
遇见更好的自我
遇见更好的自我 2021-01-25 08:54

I am wondering how to do the following- I have the following data:

dta = {
       \"fielddata\": {
           \"text1\": \"4B030C2E-3D53-4DF8-A3535EF377B45DE5\",         


        
相关标签:
3条回答
  • 2021-01-25 09:00
    var val = "fielddata.text1",
        acc = dta,               // reference the base object
        parts = val.split('.'),  // split the val into an Array of individual parts
        i;
    
      // Iterate the parts, updating acc each time
    for( i = 0; i < parts.length; i++ )
        acc = acc[parts[i]];
    
    0 讨论(0)
  • 2021-01-25 09:18

    getter

    exports.getDeep = function(field, object){
      var parts = field.split('.');
      var value = object;
      // Iterate the parts, updating value each time
      for( var i = 0; i < parts.length; i++ ){
          value = value[parts[i]];
          if(i==parts.length-1){
            return JSON.parse(JSON.stringify(value))
          }
      }
    }
    

    setter

    exports.setDeep = function(field, object, newvalue){
      var parts = field.split('.');
      for( var i = 0; i < parts.length; i++ ){
          if(i==parts.length-1){
            object[parts[i]] = newvalue
            return object
          }
      }
    }
    
    0 讨论(0)
  • 2021-01-25 09:20

    Another option is JSONPath. For relatively simple usecases, doing it manually is likely a better solution, but with greater complexity, I might use something more formalized.

    And while I hate to suggest it, there's always eval('dta.fielddata.text1')

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