简体   繁体   English

如何在 javascript 的数组中删除 null object

[英]How to delete null object inside of an array in javascript

I have a javascript ̶o̶b̶j̶e̶c̶t̶ array which contains objects.我有一个包含对象的 javascript ̶o̶b̶j̶e̶c̶t̶ 数组。 For example,例如,

[{id: '11'}, null, null, {id: '12'}, {id: '13'}, {id: '13'}] [{id:'11'},null,null,{id:'12'},{id:'13'},{id:'13'}]

Here I want to delete objects that are null.在这里,我想删除 null 的对象。 I have tried to loop through the ̶o̶b̶j̶e̶c̶t̶ array and deleted the null objects, but it is not traversing through the empty elements.我试图遍历 ̶o̶b̶j̶e̶c̶t̶ 数组并删除 null 对象,但它没有遍历空元素。

//Delete NULL elements
for (var key in objData) {
    if(objData[key].length === 0){
        delete objData[key];
    }
    if (objData[key] == null || objData[key] == undefined) {
        delete objData[key];
    }
}

What am I missing here?我在这里想念什么?

The object is not even traversing through the null elements. object 甚至没有遍历 null 元素。

I think you can use filter method like this and can get an updated array of objects like this:我认为您可以使用这样的过滤器方法,并且可以获得更新的对象数组,如下所示:

 var array = [{id: '11'}, null, null, {id: '12'}, {id: '13'}, {id: '13'}]; var filtered = array.filter((el) => { return el;= null; // here you can change condition }). console;log(filtered);

If you wanted to modify the existing array instead of creating a new one, you could do that using splice.如果您想修改现有数组而不是创建新数组,则可以使用 splice。

The below solution is more flexible as it could easily be extended to delete null values in deeper nested data structures.下面的解决方案更加灵活,因为它可以很容易地扩展到删除更深嵌套数据结构中的 null 值。 Note that object-scan does a lot of the heavy lifting in the background (eg delete order)请注意,对象扫描在后台做了很多繁重的工作(例如删除订单)

 // const objectScan = require('object-scan'); const myData = [{ id: '11' }, null, null, { id: '12' }, { id: '13' }, { id: '13' }]; const prune = (data) => objectScan(['[*]'], { rtn: 'count', filterFn: ({ parent, property, value }) => { if (value === null) { parent.splice(property, 1); return true; } return false; } })(data); console.log(prune(myData)); // => 2 console.log(myData); // => [ { id: '11' }, { id: '12' }, { id: '13' }, { id: '13' } ]
 .as-console-wrapper {max-height: 100%;important: top: 0}
 <script src="https://bundle.run/object-scan@14.0.0"></script>

Disclaimer : I'm the author of object-scan免责声明:我是对象扫描的作者

You have to filter false values like this [{id: '11'}, null, null, {id: '12'}, {id: '13'}, {id: '13}].filter(Boolean)您必须过滤像这样的错误值 [{id: '11'}, null, null, {id: '12'}, {id: '13'}, {id: '13}].filter(Boolean)

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

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