【问题标题】:How to remove all blank Objects from an Object in Javascript?如何在Javascript中从一个对象中删除所有空白对象?
【发布时间】:2020-12-05 12:22:23
【问题描述】:

如何在Javascript中从一个对象中删除所有空白对象? 像这样

const test={a:'a',b:{},c:{c:{}}}

如何获得结果:

test={a:'a'}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    这是另一种方式,其中包含一些细节。

    需要/记住:

    1. 进入 obj 意味着循环
    2. 识别对象:避免元素不是object typed and only checks for object typed
    3. 深入:对于嵌套对象,recursive pattern 很方便。
      (小心避免使用递归函数执行的无限循环)
    4. 如果为空,则删除/移除 obj

    代码sn-p:

     const test = {
          a: "a", b: {},
          c: { c: {} },
          d: {
            d: { e: {} }
          },
        }
    
        function checkObjEmptiness(obj) {
          // increases readability
          // avoid "typeof" checking as "typeof [] === 'object' // returns true"
        
          let isObject = (x) => x && x instanceof Object, 
              isEmpty  = (x) => x && !Object.keys(x).length;
    
    
          // 1. loops over obj to check each elements emptiness
          for (let k in obj) {
            // 2. check for object within object based on: isObject && !isEmpty
            // 3. if object and not empty --> re-apply processus
            if (isObject(obj[k]) && !isEmpty(obj[k])) checkObjEmptiness(obj[k]);
    
            // handles deletion on obj if empty [ or value if empty ]
            //if (isEmpty(obj[k]) || !obj[k]) delete obj[k]; // handles empty values
    
            // 4. deletes object if empty
            if (isEmpty(obj[k])) delete obj[k]; //handles empty object
          }
          return obj;
        }
    
        checkObjEmptiness( test )

    【讨论】:

      【解决方案2】:

      下面的递归函数将删除所有空对象。

      function removeEmpty(obj) {
          Object.keys(obj).forEach(k => {
              if (obj[k] && typeof obj[k] === 'object' && removeEmpty(obj[k]) === null) {
                  delete obj[k];
              }
          });
      
          if (!Object.keys(obj).length) {
              return null;
          }
      }
      

      工作演示

      function removeEmpty(obj) {
          Object.keys(obj).forEach(k => {
              if (obj[k] && typeof obj[k] === 'object' && removeEmpty(obj[k]) === null) {
                  delete obj[k];
              }
          });
      
          if (!Object.keys(obj).length) {
              return null;
          }
      }
      
      const test1 = {data:{a:{}}};
      removeEmpty(test1);
      console.log(test1); // {}
      
      const test2 = {data:{a:{}, b:1}};
      removeEmpty(test2);
      console.log(test2); // {data:{b: 1}}
      
      const test3 = {a:'a',b:{},c:{c:{}}};
      removeEmpty(test3);
      console.log(test3); // {a: 'a'}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-08
        • 1970-01-01
        • 2017-03-23
        • 2022-06-11
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多