[英]Remove null elements from array jquery
我有我的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">
相同值的papersupply和PaperConsum的多個輸入,在javascript中,我正在使用像這樣的map函數為相同的值創建一個數組
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,則應該為null,然后還應該刪除第二個數組的相同索引。
這是演示小提琴演示
您可以從.map()返回undefined來忽略空值。
在回調函數中,這是指每次迭代的當前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();
演示: 小提琴
更新資料
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)
演示: 小提琴
您可以添加過濾器:
$('.PaperSupply').map(function(){
return $(this).val().trim();
}).get().filter(Boolean);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.