Set nested item in object/array from array of keys

前端 未结 3 1746
既然无缘
既然无缘 2021-01-22 03:46

I have a bunch of JSON with multiple objects, arrays, strings, booleans, numbers etc. which are stored in one object at the root level and component.

Here is a sample:

相关标签:
3条回答
  • 2021-01-22 04:24

    Below is a simple version of Nina's answer (the one using reduce).

    Hope this helps you get what's going on behind that.

    const setValueByPathArray = (object, path, value) => {
      let i = 0
      let reference = object
      while (i < path.length - 1) {
        const currentPath = path[i]
        reference = reference[currentPath]
        i += 1
      }
      const lastPath = path[path.length - 1]
      reference[lastPath] = value
      return object
    }
    
    const config = { theme: { auto: { sensor: "sensor.sn1_ldr", below: 600 }, ui: { cards: { round: false, elevation: 1 } } } }
    const path = ["theme", "auto", "sensor"];
    
    setValueByPathArray(config, path, 'foo')
    
    0 讨论(0)
  • 2021-01-22 04:24
    1. Use Object.key to get the key Array:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

    1. Use recursion to loop through.

      const object1 = {
        "theme": {
          "auto": {
            "sensor": "sensor.sn1_ldr",
            "below": 600
          },
          "ui": {
            "cards": {
              "round": false,
              "elevation": 1
            }
          },
      
        },  
      }
      
      var result = [];
      see(object1);
      console.log(result);
      
      function see (obj){
          var k = Object.keys(obj)
          for (var i = 0; i < k.length; i++){
              result.push(k[i]);
              if (obj[k[i]] instanceof Object){
                  see(obj[k[i]]);
              }
          }
      }
      
    0 讨论(0)
  • 2021-01-22 04:33

    You could store the last key and reduce the object by taking the keys from the path.

    function setValue(object, path, value) {
        var last = path.pop();
        path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
    }
    
    var config = { theme: { auto: { sensor: "sensor.sn1_ldr", below: 600 }, ui: { cards: { round: false, elevation: 1 } } } },
        path = ["theme", "auto", "sensor"];
    
    setValue(config, path, 'foo');
    
    console.log(config);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

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