简体   繁体   English

从数组jQuery中删除空元素

[英]Remove null elements from array jquery

I have my html like 我有我的HTML喜欢

  <input  type="text" class="form-control PaperSupply">` 
  <input  type="text" class="form-control PaperSupply">`
 <input  type="text" class="form-control PaperConsum">
 <input  type="text" class="form-control PC">

multiple inputs for same value papersupply and PaperConsum, in javascript i am creating an array for same value using map function like this 相同值的papersupply和PaperConsum的多个输入,在javascript中,我正在使用像这样的map函数为相同的值创建一个数组

 var paperSupply = $('.PaperSupply').map(function(){return $(this).val();}).get(); 
 var PaperConsum= $('.PaperConsum').map(function(){return $(this).val();}).get(); 

now in json i want if any element of these array is null remove that element from array. 现在在json中,我希望如果这些数组的任何元素为null,则从数组中删除该元素。

for example: 例如:

{"paperSupply":["","2","3","","5"],"paperConsum":["1","","4","5","6"]}

if this is json from above code, then i want above json like this, 如果这是上面代码中的json,那么我想要这样的json,

{"paperSupply":["2","3","5"],"paperConsum":["","4","6"]}

if any index of paperSupply is null it should be null then same index for second array should also be remove . 如果paperSupply的任何索引为null,则应该为null,然后还应该删除第二个数组的相同索引。

this is demo fiddle DEMO 这是演示小提琴演示

You can return undefined from .map() to ignore the empty values. 您可以从.map()返回undefined来忽略空值。

Within the callback function, this refers to the current DOM element for each iteration. 在回调函数中,这是指每次迭代的当前DOM元素。 The function can return an individual data item or an array of data items to be inserted into the resulting set. 该函数可以返回要插入到结果集中的单个数据项或数据项数组。 If an array is returned, the elements inside the array are inserted into the set. 如果返回数组,则将数组内的元素插入到集合中。 If the function returns null or undefined, no element will be inserted. 如果函数返回null或undefined,则不会插入任何元素。

var paperSupply = $('.PaperSupply').map(function () {
    return $(this).val().trim() || undefined; //use trim only if you want to discard inputs with space only
}).get();

Demo: Fiddle 演示: 小提琴


Update 更新资料

var PaperConsum = [],
    $PaperConsums = $('.PaperConsum');
var paperSupply = $('.PaperSupply').map(function (i, el) {
    var value = $(this).val().trim(); //use trim only if you want to discard inputs with space only
    if (value) {
        PaperConsum.push($PaperConsums.eq(i).val() || '');
        return value;
    }
}).get();

console.log(paperSupply, PaperConsum)

Demo: Fiddle 演示: 小提琴

You can add filter: 您可以添加过滤器:

$('.PaperSupply').map(function(){
    return $(this).val().trim();
}).get().filter(Boolean);

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

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