Set nested item in object/array from array of keys

前端 未结 3 1748
既然无缘
既然无缘 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

    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]]);
              }
          }
      }
      

提交回复
热议问题