javascript - 从复杂输出中删除空对象/对象
问题描述
使用地图(在嵌套 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' } ]
解决方案
您可以通过检查对象是否不为空来过滤数组
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);
}
推荐阅读
- c++ - gmock:在 std::vector 的一系列元素上调用匹配器
- java - RecyclerView 有很多项目加载太慢
- javascript - “元素”类型缺少“OfferProps”类型的以下属性:id、firstName、city、price 和另外 2 个。TS2740
- sql - 找到每艘船上的水手
- javascript - 错误:无法从路径或包中检测节点名称
- rust - 当仅另一个特征参数需要生命周期时,编译器会抱怨缺少 PhantomData
- python - 将字典转换为列表,然后从列表转换回字典,但具有相同的值
- amazon-web-services - 我只需要为 3 个云提供商 AWS、GCP、阿里巴巴创建集中式 DNS/LDAP
- javascript - onClick 切换数组对象
- sql - 添加具有基于另一个日期时间列的值的日期时间列