Node.js - 从JSON对象中删除null元素

问题描述 投票:4回答:5

我试图从JSON对象中删除null / empty元素,类似于python webutil / util.py - > trim_nulls方法的功能。我可以使用Node内置的东西,还是自定义方法。

例:

var foo = {a: "val", b: null, c: { a: "child val", b: "sample", c: {}, d: 123 } };

预期结果:

foo = {a: "val", c: { a: "child val", b: "sample", d: 123 } };
javascript json node.js
5个回答
5
投票

我不知道为什么人们会对我的原始答案进行评价,这是错误的(猜测它们看起来太快了,就像我做的那样)。无论如何,我不熟悉节点,所以我不知道它是否包含了这个,但我认为你需要这样的东西来直接JS:

var remove_empty = function ( target ) {

  Object.keys( target ).map( function ( key ) {

    if ( target[ key ] instanceof Object ) {

      if ( ! Object.keys( target[ key ] ).length && typeof target[ key ].getMonth !== 'function') {

        delete target[ key ];

      }

      else {

        remove_empty( target[ key ] );

      }

    }

    else if ( target[ key ] === null ) {

      delete target[ key ];

    }

  } );


  return target;

};

remove_empty( foo );

我没有尝试使用foo中的数组 - 可能需要额外的逻辑来处理不同的方式。


2
投票

感谢所有帮助..我使用与foo一起使用的所有注释中的反馈拼凑了以下代码。

function trim_nulls(data) {
  var y;
  for (var x in data) {
    y = data[x];
    if (y==="null" || y===null || y==="" || typeof y === "undefined" || (y instanceof Object && Object.keys(y).length == 0)) {
      delete data[x];
    }
    if (y instanceof Object) y = trim_nulls(y);
  }
  return data;
}

2
投票

我发现这是最优雅的方式。另外我相信JS引擎已经针对它进行了大量优化。

使用内置的JSON.stringify(value[, replacer[, space]])功能。文件是here

示例是从外部API检索一些数据,相应地定义一些模型,得到无法定义或不需要的所有内容的结果和印章的上下文:

function chop (obj, cb) {
  const valueBlacklist = [''];
  const keyBlacklist = ['_id', '__v'];

  let res = JSON.stringify(obj, function chopChop (key, value) {
    if (keyBlacklist.indexOf(key) > -1) {
      return undefined;
    }

    // this here checks against the array, but also for undefined
    // and empty array as value
    if (value === null || value === undefined || value.length < 0 || valueBlacklist.indexOf(value) > -1) {
      return undefined;
    }
    return value;
 })
 return cb(res);
}

在您的实施中。

// within your route handling you get the raw object `result`
chop(user, function (result) {
   var body = result || '';
   res.writeHead(200, {
      'Content-Length': Buffer.byteLength(body),
      'Content-Type': 'application/json'
   });
   res.write(body);
   // bang! finsihed.
   return res.end();
});

// end of route handling

2
投票

你可以像这样使用:

Object.keys(foo).forEach(index => (!foo[index] && foo[index] !== undefined) && delete foo[index]);

1
投票

您只需使用for循环过滤并输出到新的干净对象:

var cleanFoo = {};
for (var i in foo) {
  if (foo[i] !== null) {
    cleanFoo[i] = foo[i];
  }
}

如果您还需要处理子对象,则需要递归。

© www.soinside.com 2019 - 2024. All rights reserved.