如何在 JavaScript 中移除对象中的所有空对象?


我们的任务是学习如何从 JavaScript 对象中移除所有空对象。让我们考虑以下对象:

const details =
{
   name: 'John',
   age: {},
   marks: { marks: {} }
}

我们需要移除上面的空对象。可以使用 `forEach()` 结合 `typeof` 和 `delete` 来移除空对象。让我们深入文章,更好地理解如何移除空对象。

使用 `reduce()`

使用 **`reduce()`** 方法,对数组的每个元素运行一个 reducer 函数。**`reduce()`** 方法只返回函数的最终结果。对于空数组元素,**`reduce()`** 方法不会运行该函数。**`reduce()`** 方法不会改变原始数组。

语法

以下是 **`reduce()`** 的语法:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

示例

在下面的示例中,我们使用 **`reduce()`** 运行脚本以从对象中移除空对象。

<!DOCTYPE html>
<html>
   <body>
      <script>
      let details = {
         "company":"Tutorialspoint","school": '',"college": '',
         "address": "kavuri incor9"
      };
      let result = Object.entries(details).reduce((a,[k,v]) => (v == '' ? a : (a[k]=v, a)), {});
      document.write(JSON.stringify(result))
      </script>
   </body>
</html>

脚本执行后,会在网页上生成一个输出,其中包含一个打印的数组,该数组包含具有值的的对象,所有空对象都被移除。

使用 `forEach()`

对于数组中的每个元素,**`forEach()`** 方法都会执行指定的函数一次。

语法

以下是 **`forEach()`** 的语法:

array.forEach(function(currentValue, index, arr), thisValue)

示例

考虑以下示例,我们使用 **`forEach()`** 从对象中移除空对象。

<!DOCTYPE html>
<html>
   <body>
      <script>
         const vehicles = {
            c: 'BENZ',
            a: 'BMW',
            r: '',
            s: ''
         };
         Object.keys(vehicles).forEach(key => {
            if(!vehicles[key])
            delete vehicles[key]
         });
         document.write(JSON.stringify(vehicles))
      </script>
   </body>
</html>

运行上述脚本后,将弹出输出窗口,显示已打印的数组,该数组包含网页上具有值的的对象。

示例

让我们看下面的例子,这里我们使用展开语法和 **`forEach()`** 运行脚本,从对象中移除空对象。

<!DOCTYPE html>
<html>
   <body>
      <script>
      let bikes = {
         bike1: "Rx100",
         bike2: '',
         bike3: '',
         bike4: "vespa"
      };
      let removeobj = {};
      Object.keys(bikes).forEach(val => {
         const newVal = bikes[val];
         removeobj = newVal ? { ...removeobj,
            [val]: newVal
         } : removeobj;
      });
      document.write(JSON.stringify(removeobj));
   </script>
   </body>
</html>

脚本执行后,将弹出输出窗口,触发事件并在网页上显示包含值的的对象数组。

更新于:2023年4月21日

3K+ 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.