Iterating Array of Objects in javascript

后端 未结 9 1368
闹比i
闹比i 2020-12-24 13:31

I am having an array that consists the objects with a key, value how can we iterate each object for caste and id.

[
    Object {
           


        
相关标签:
9条回答
  • 2020-12-24 13:59

    Use jQuery.each:

    $.each([your array of objects], function(index, value) {
      // Do what you need, for example...
      alert(index + ': ' + value);
    });
    
    0 讨论(0)
  • 2020-12-24 14:00

    To iterate over an array filled with stuff in jQuery use $.each, to iterate over an Object for its properties use for..in

    0 讨论(0)
  • 2020-12-24 14:04

    Using jQuery.each():

    var array = [
       {caste: "Banda", id: 4},
       {caste: "Bestha", id: 6}
    ];
        
    $.each(array, function( key, value ) {
      console.log('caste: ' + value.caste + ' | id: ' +value.id);
    }
    
    );
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 2020-12-24 14:07
    var array = [{caste: "Banda", id: 4}, {caste: "Bestha", id:6}];
    var length = array.length;
    for (var i = 0; i < length; i++) {
       var obj = array[i];
       var id = obj.id;
       var caste = obj.caste;
    }
    
    0 讨论(0)
  • 2020-12-24 14:10

    Example code:

    var list = [
        { caste:"Banda",id:4},
        { caste:"Bestha",id:6},
    ];
        
    for (var i=0; i<list.length; i++) {
        console.log(list[i].caste);
    }

    It's just an array, so, iterate over it as always.

    0 讨论(0)
  • 2020-12-24 14:16

    you can use jquery to iterate through all the objects jQuery wants you to fill a callback function, which jquery will call back. The first input parameter will be given the key and the second input parameter the value:

    $.each(dataList, function(index, object) {
       $.each(object,function(attribute, value){
          alert(attribute+': '+value);
       });
    });
    

    documentation: http://api.jquery.com/jQuery.each/

    0 讨论(0)
提交回复
热议问题