简体   繁体   English

从 JSON 对象中删除空数据

[英]Remove empty data from a JSON Object

I have a Typescript class in which I collect a JSON Object with some empty parameters, what I want is to filter that object to obtain another Object but without the empty data of the first one.我有一个 Typescript 类,我在其中收集了一个带有一些空参数的 JSON 对象,我想要的是过滤该对象以获取另一个对象,但没有第一个对象的空数据。

This is my JSON object:这是我的 JSON 对象:

{ Country: 'Colombia',
  Ser: 'ok',
  Ins: '',
  BBDD: 'ok',
  Mid: '',
  Ata: '',
  'Branch Ser': 'ok',
  Service: '' }

This is what I want to achieve:这就是我想要实现的目标:

{ Country: 'Colombia',
      Ser: 'ok',
      BBDD: 'ok',
      'Branch Ser': 'ok' }

 const allData = { Country: 'Colombia', Ser: 'ok', Ins: '', BBDD: 'ok', Mid: '', Ata: '', 'Branch Ser': 'ok', Service: '' }; const filteredData = Object.entries(allData).reduce((x, [k, v]) => { if (v) { // not ( null, undefined, empty string) x[k] = v; } return x; }, {} as any); console.log(filteredData);

You can use Object.entries function to list object as key value pairs and then use the Array.reduce to filter out the falsy values.您可以使用Object.entries函数将对象列为键值对,然后使用Array.reduce过滤掉虚假值。

 const allData = { Country: 'Colombia', Ser: 'ok', Ins: '', BBDD: 'ok', Mid: '', Ata: '', 'Branch Ser': 'ok', Service: '' }; const filteredData = Object.fromEntries(Object.entries(allData).filter(([_, value]) => value)); console.log(filteredData);

Above is a simple one-line solution to do it.以上是一个简单的单行解决方案。 Using JS' Object.fromEntries() really helps.使用 JS 的Object.fromEntries()真的很有帮助

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

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