首页 > 解决方案 > 从复杂输出中删除空对象/对象

问题描述

使用地图(在嵌套 json 中获取必要元素的几个地图)函数我试图根据所需的模板从 Neo4j 数据库中获取输出。在最后一张地图中,我正在构建所需输出的一部分,并将其存储在变量中:

 px.segments.map(function(pathSegment){                                                                                          
 individual_path.push({                          
 "start": pathSegment.start.properties.name,
 "weight": pathSegment.relationship.properties.Weight.low,
  "end": pathSegment.end.properties.name}); 
  })

然后,根据我在 DB 和 Cypher 查询中使用的内容,在某些情况下,我在执行时得到:

 console.log(individual_path);

我得到类似的东西:

 [ { start: 'title', weight: 39, end: 'metadata' } ]
 [ { start: 'title', weight: 39, end: 'metadata' } ]
 [ { start: 'title', weight: 39, end: 'metadata' } ]
 [ { start: 'title', weight: 39, end: 'metadata' },
   { start: 'metadata', weight: 39, end: 'filmID' } ]
 [ { start: 'title', weight: 39, end: 'metadata' },
   { start: 'metadata', weight: 39, end: 'filmID' } ]
 []
 [ { start: 'movieID', weight: 39, end: 'moviesSchema' } ]
 [ { start: 'movieID', weight: 39, end: 'moviesSchema' },
   { start: 'moviesSchema', weight: 39, end: 'title' } ]
 [ { start: 'movieID', weight: 39, end: 'moviesSchema' },
   { start: 'moviesSchema', weight: 39, end: 'title' },
   { start: 'title', weight: 39, end: 'metadata' } ]

我的目标是避免可能出现在输出中的空对象,因为我需要完全以形式(开始:,重量:,结束:)使用它。最后我需要有类似的东西(没有空):

 [ { start: 'title', weight: 39, end: 'metadata' } ]
 [ { start: 'title', weight: 39, end: 'metadata' } ]
 [ { start: 'title', weight: 39, end: 'metadata' } ]
 [ { start: 'title', weight: 39, end: 'metadata' },
   { start: 'metadata', weight: 39, end: 'filmID' } ]
 [ { start: 'title', weight: 39, end: 'metadata' },
   { start: 'metadata', weight: 39, end: 'filmID' } ]
 [ { start: 'movieID', weight: 39, end: 'moviesSchema' } ]
 [ { start: 'movieID', weight: 39, end: 'moviesSchema' },
   { start: 'moviesSchema', weight: 39, end: 'title' } ]
 [ { start: 'movieID', weight: 39, end: 'moviesSchema' },
   { start: 'moviesSchema', weight: 39, end: 'title' },
   { start: 'title', weight: 39, end: 'metadata' } ]

标签: javascript

解决方案


您可以通过检查对象是否不为空来过滤数组

let array = [{},{},{ start: 'title', weight: 39, end: 'metadata' },{ start: 'title', weight: 39, end: 'metadata' },{ start: 'title', weight: 39, end: 'metadata' },{ start: 'title', weight: 39, end: 'metadata' },{},{}];

array = array.filter(obj => Object.entries(obj).length !== 0 );
console.log(array);

但是在问题中,您有一个空数组[],我认为您想删除它,然后执行。

if (individual_path.length){
    console.log(individual_path);
}

推荐阅读