2015-05-09 140 views
0

我有我的HTML等从阵列的jquery删除null元素

<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"> 

为相同的值papersupply和PaperConsum, 在javascript我使用映射函数这样

var paperSupply = $('.PaperSupply').map(function(){return $(this).val();}).get(); 
var PaperConsum= $('.PaperConsum').map(function(){return $(this).val();}).get(); 
创建相同的值的阵列的多个输入

现在在json我想要如果这些数组的任何元素为null从数组中删除该元素。

例如:

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

,如果这是JSON从上面的代码, 然后我想以上这样JSON,

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

如果paperSupply的任何指数为null它应该是空值,则第二个数组的相同索引也应该删除。

这是演示小提琴DEMO

回答

2

您可以返回undefined从.map()忽略空值。

在回调函数中,这指的是每个迭代的当前DOM元素 。该函数可以返回一个单独的数据项或一组要插入到结果集中的数据项。如果返回一个 数组,则将数组内的元素插入到 集合中。 如果函数返回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(); 

演示:Fiddle


更新

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) 

演示:Fiddle

+0

@downvoter,我错过了什么 –

+0

为什么这downvote是正确 –

+0

感谢的答案,但你只从数组删除元素,而不是去除同一索引第二个数组元素。如果paperSupply [0]为null,那么paperConsum [0]也应该为null –

0

您可以添加过滤器:

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

谢谢你的回答,但你只是从数组中删除元素,而不是从同一索引中删除第二个数组元素。如果paperSupply [0]为null,则paperConsum [0]也应该为null –