Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set a condition in an array using jquery?

I want to customise an array to some types using jquery

$(function(){
    let i = 1;
    $('.dataTable thead th').each(function(index) {
        let array = {
            text:$(this).text(),
            if($(this).hasClass("datepicker")) {
                type:"number"
            }
        };
    });
});

I want to say that if this has class datepicker so set the type:number and else set the type:text

like image 433
hamed dehghan Avatar asked May 10 '26 22:05

hamed dehghan


2 Answers

What you have is not an array. Perhaps you meant

$(function() {
  var arr = [];
  $('.dataTable thead th').each(function(index) {
    arr.push({
      "type": $(this).hasClass("datepicker")?"number":"text";
    });
  });
});

or

$(function() {
  var arr = [];
  $('.dataTable thead th').each(function(index) {
    arr.push({
      "text": $.trim($(this).text()) || "n/a",
      "type": $(this).hasClass("datepicker")?"number":"text";
    });
  });
});

You can streamline this using http://api.jquery.com/map/

like image 67
mplungjan Avatar answered May 12 '26 12:05

mplungjan


try

let table= [...document.querySelectorAll('.dataTable thead th')];

table.forEach(e=> {
 let arr = {
   type: e.classList.contains('datepicker') ? 'text' : 'number',
   text: e.innerText,
 }
 console.log(arr);
});
<table class="dataTable"><thead>
  <th>A</th>
  <th class='datepicker'>B</th>
  <th>C</th>
</thead></table>
like image 44
Kamil Kiełczewski Avatar answered May 12 '26 12:05

Kamil Kiełczewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!