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

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

Given:

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


        
相关标签:
7条回答
  • 2020-11-28 23:55

    Not a direct answer to your question, though I thing it's worth mentioning it, because your question seems like fitting in the general case of "getting things by name in a key-value storage".

    If you are not tight to the way "peoples" is implemented, a more JavaScript-ish way of getting the right guy might be :

    var peoples = {
      "bob":  { "dinner": "pizza" },
      "john": { "dinner": "sushi" },
      "larry" { "dinner": "hummus" }
    };
    
    // If people is implemented this way, then
    // you can get values from their name, like :
    var theGuy = peoples["john"];
    
    // You can event get directly to the values
    var thatGuysPrefferedDinner = peoples["john"].dinner;
    

    Hope if this is not the answer you wanted, it might help people interested in that "key/value" question.

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