Home > OS >  How to fetch last value in the for loop using javascript?
How to fetch last value in the for loop using javascript?

Time:11-14

enter image description here

    var new_data = $.parseJSON(data);
        for (var j = 0; j < new_data.all_soa_details.length; j  ) {
          var td7_contact = new_data.all_soa_details[j].bal; //100,200,200,50 . here i need to fecth 50 only
          let td77_contact = Math.abs(td7_contact);
        }

i am getting values 100, 200,40,60, 50.. Here i need to fetch 50 becoz its last valuje in the for loop .How to get this last value?

CodePudding user response:

new_data.all_soa_details[new_data.all_soa_details.length - 1].bal

should give you the expected result

CodePudding user response:

Try this out, I just wrote a code for you..

let new_data = {
      all_soa_details: [
        {
          bal: [1, 2, 3, 45],
        },
        {
          bal: [1, 2, 3, 45],
        },
      ],
    };

    for (var j = 0; j < new_data.all_soa_details.length; j  ) {
      var td7_contact = new_data.all_soa_details[j].bal; //100,200,200,50 . here i need to fecth 50 only
      let td77_contact = Math.abs(td7_contact);
    }

    // let findOut;
    // for (const lastIter of td7_contact) {
    //   findOut = lastIter; //Last iteration value stored in each iteration.
    // }
    // console.log(findOut);

    // Main code ....
    console.log(
      new_data.all_soa_details[0].bal[
        new_data.all_soa_details[0].bal.length - 1
      ]
    );

    for (let i = 0; i < new_data.all_soa_details.length; i  ) {
      console.log(
        new_data.all_soa_details[i].bal[
          new_data.all_soa_details[i].bal.length - 1
        ]
      );
    }
  • Related