Iterating Array of Objects in javascript

后端 未结 9 1369
闹比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 14:17

    In plain JavaScript you can do this:

    var array = [{caste: "Banda", id: 4}, {caste: "Bestha", id:6}];
    
    array.forEach(function(element, index) {
        console.log(element.id+" "+element.caste);
    });
    

    The callback function is called with a third parameter, the array being traversed. For learn more!

    So, you don't need to load jQuery library.

    Greetings.

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

    Arrow functions are modern these days

    Using jquery $.each with arrow function

     var array = [
        {caste: "Banda", id: 4},
        {caste: "Bestha", id: 6}
     ];
    
     $.each(array, ( key, value ) => {
         console.log('caste: ' + value.caste + ' | id: ' +value.id);
     });
    

    Using forEach with arrow function

      array.forEach((item, index) => {
          console.log('caste: ' + item.caste + ' | id: ' +item.id);
      });
    

    Using map with arrow function. Here map returns a new array

      array.map((item, index) => {
          console.log('caste: ' + item.caste + ' | id: ' +item.id);
      });
    
    0 讨论(0)
  • 2020-12-24 14:23

    The forEach loop accepts an iterator function and, optionally, a value to use as "this" when calling that iterator function.

     var donuts = [
        { type: "Jelly", cost: 1.22 },
        { type: "Chocolate", cost: 2.45 },
        { type: "Cider", cost: 1.59 },
        { type: "Boston Cream", cost: 5.99 }
    ];
    
    donuts.forEach(function(theDonut, index) {
        console.log(theDonut.type + " donuts cost $"+ theDonut.cost+ " each");
    });
    

    Subsequently it can also be broken down to this

    var donuts = [
      { type: "Jelly", cost: 1.22 },
      { type: "Chocolate", cost: 2.45 },
      { type: "Cider", cost: 1.59 },
      { type: "Boston Cream", cost: 5.99 }
    ];
    
    
    function ShowResults(donuts) {  
        console.log(donuts.type + " donuts cost $"+ donuts.cost+ " each");  
    }
    
    donuts.forEach(ShowResults);
    
    0 讨论(0)
提交回复
热议问题