How do you get an index in $.each?



  • It's like, $.each an index can be obtained without let i = 0; and i++; ?

    let obj = {
      423: 123,
      433: 2354,
      653: 345,
      783: 534534,
    };
    

    let i = 0;
    $.each(obj, function(k, v) {
    console.log(i, k, v);
    i++;
    });

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



  • There's a good way. Object.entries()

    He works like this:

    let obj = {
      423: 123,
      433: 2354,
      653: 345,
      783: 534534,
    };
    console.log(obj);    
    console.log(Object.entries(obj));

    For your case:

    let obj = {
      423: 123,
      433: 2354,
      653: 345,
      783: 534534,
    };
    

    $.each(Object.entries(obj), function(i, [k, v]) { // здесь первый
    // параметр i,
    // а второй [k,v]
    // (деструкторизация)
    console.log(i, k, v);
    });

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    Speaking of which, there's a reverse Object. fromEntries.

    let obj = [
    ["423",123],
    ["433",2354],
    ["653",345],
    ["783",534534]
    ];
    console.log(obj);
    console.log(Object.fromEntries(obj));


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2