get one item from an array of name,value JSON

后端 未结 7 968
孤城傲影
孤城傲影 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:20

    The easiest approach which I have used is

    var found = arr.find(function(element) {
             return element.name === "k1";
     });
    
    //If you print the found :
    console.log(found);
    => Object { name: "k1", value: "abc" }
    
    //If you need the value
    console.log(found.value)
    => "abc"
    

    The similar approach can be used to find the values from the JSON Array based on any input data from the JSON.

提交回复
热议问题