I have my html like
<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
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.
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,
{"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 .
this is demo fiddle DEMO
You can return undefined from .map() to ignore the empty values.
Within the callback function, this refers to the current DOM element for each iteration. 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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.