How to find index of an object by key and value in an javascript array

后端 未结 7 1472
既然无缘
既然无缘 2020-11-28 22:52

Given:

var peoples = [
  { \"attr1\": \"bob\", \"attr2\": \"pizza\" },
  { \"attr1\": \"john\", \"attr2\": \"sushi\" },
  { \"attr1\": \"lar         


        
7条回答
  •  暖寄归人
    2020-11-28 23:38

    Using jQuery .each()

    var peoples = [
      { "attr1": "bob", "attr2": "pizza" },
      { "attr1": "john", "attr2": "sushi" },
      { "attr1": "larry", "attr2": "hummus" }
    ];
    
    $.each(peoples, function(index, obj) {
       $.each(obj, function(attr, value) {
          console.log( attr + ' == ' + value );
       });
    });

    Using for-loop:

    var peoples = [
      { "attr1": "bob", "attr2": "pizza" },
      { "attr1": "john", "attr2": "sushi" },
      { "attr1": "larry", "attr2": "hummus" }
    ];
    
    for (var i = 0; i < peoples.length; i++) {
      for (var key in peoples[i]) {
        console.log(key + ' == ' + peoples[i][key]);
      }
    }

提交回复
热议问题