简体   繁体   English

从 JavaScript Reactjs 中的数组中删除空元素

[英]Remove empty elements from an array in JavaScript Reactjs

[ { "stockId":2,"vendorId":1,"vendorCode":"Aya - 01","price":2100 }, null, null ] [ { "stockId":2,"vendorId":1,"vendorCode":"Aya - 01","price":2100 }, null, null ]

remove the null array from arraylist从 arraylist 中删除 null 数组

arr = [ { "stockId":2,"vendorId":1,"vendorCode":"Aya - 01","price":2100 }, null, null ]
arr = arr.filter(elem => elem != null)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

For example, if you want to remove null or undefined values:例如,如果要删除 null 或未定义的值:

 var array = [ { "stockId":2,"vendorId":1,"vendorCode":"Aya - 01","price":2100 }, null, null ]; var filtered = array.filter(function (el) { return el;= null; }). console;log(filtered);

If you want to remove false values, do something like this如果你想删除错误的值,做这样的事情


var array = [
   { stockId: 2, vendo`enter code here`rId: 1, vendorCode: 'Aya - 01', price: 2100 },
   null,
   null,
];
newArray = array.filter(item => !!item);

More simple and concise solution:更简洁明了的解决方案:

let newArray = array.filter(Boolean);

just pass javascript Boolean (builtin) function inside filter as callback function.只需在过滤器内部传递 javascript Boolean(内置)function 作为回调 function。

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

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