2015-05-09 139 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 –