get one item from an array of name,value JSON

后端 未结 7 939
孤城傲影
孤城傲影 2020-12-13 01:33

I have this array:

var arr = [];
arr.push({name:\"k1\", value:\"abc\"});
arr.push({name:\"k2\", value:\"hi\"});
arr.push({name:\"k3\", value:\"oa\"});


        
相关标签:
7条回答
  • 2020-12-13 02:26

    Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}. If you know that the name property of each object will be unique you can store them in an object instead of an array, as follows:

    var obj = {};
    obj["k1"] = "abc";
    obj["k2"] = "hi";
    obj["k3"] = "oa";
    
    alert(obj["k2"]); // displays "hi"
    

    If you actually want an array of objects like in your post you can loop through the array and return when you find an element with an object having the property you want:

    function findElement(arr, propName, propValue) {
      for (var i=0; i < arr.length; i++)
        if (arr[i][propName] == propValue)
          return arr[i];
    
      // will return undefined if not found; you could return a default instead
    }
    
    // Using the array from the question
    var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"}
    alert(x["value"]); // displays "hi"
    
    var y = findElement(arr, "name", "k9"); // y is undefined
    alert(y["value"]); // error because y is undefined
    
    alert(findElement(arr, "name", "k2")["value"]); // displays "hi";
    
    alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property
    
    0 讨论(0)
提交回复
热议问题