繁体   English   中英

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

[英]Node.js - Remove null elements from JSON object

我正在尝试从 JSON 对象中删除空/空元素,类似于 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 } };

我不知道为什么人们会赞成我原来的答案,这是错误的(猜想他们只是看起来太快了,就像我一样)。 无论如何,我不熟悉 node,所以我不知道它是否包含一些东西,但我认为你需要这样的东西才能在直接的 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的数组尝试这个——可能需要额外的逻辑来以不同的方式处理它。

你可以这样使用:

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

你可以使用这个:

let fooText = JSON.stringify(foo);
    
let filteredFoo = JSON.parse(objectLogText, (key, value) => {if(value !== null) return value});

JSON.parse() 文档

感谢您的所有帮助.. 我已经使用与 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;
}

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

使用内置的JSON.stringify(value[, replacer[, space]])功能。 文档在这里

示例是在从外部 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

您可以使用for循环进行过滤并输出到一个新的干净对象:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM