Get Value from Key Value array

假如想象 提交于 2021-02-08 08:10:39

问题


I have an array with key value pairs.

var array=[
             {Key:"Name",Value:"Sam" },
             {Key:"Marks",Value:"50"},
             {Key:"Subject",Value:"English"},
          ];

I want to push Value of object whose Key is 'Subject' into a variable. I tried to see how Value can be accessed but failed at the very first step. How can this be done?

for (var key in array[0])
{
    console.log(key[i].Value); //error:  Cannot read property 'Value' of undefined
}

How can I push Value of object whose Key is 'Subject' into a variable?


回答1:


Your for-in loop is on the array[0] object, so key is a key (property name) for that object. So this:

console.log(key[i].Value);

should be

console.log(array[0][key].Value);

But, given what you've said you want to do, I'm not seeing any need for a for-in loop:

I want to push Value of object whose Key is 'Subject' into a variable.

Array#find (which is new in ES2015 -- aka ES6 -- but easily shimmed/polyfilled) is useful for this:

var entry = array.find(function(e) { return e.Key === "Subject"; });
if (entry) {
    theVariable = entry.Value;
}

If you're using ES2015 (which still means transpiling, for now), you can use an arrow function to be more concise:

let entry = array.find(e => e.Key === "Subject");
if (entry) {
    theVariable = entry.Value;
}

But if you want to stick to things in ES5 and earlier, there's Array#some:

array.some(function(e) {
    if (e.Key === "Subject") {
        theVariable = e.Value;
        return true; // stops the "loop"
    }
});



回答2:


sorry i misunderstood the question before - edited

I suggest using the jQuery.each() method for this

var array=[ {Key:"Name",Value:"Sam" }, {Key:"Marks",Value:"50"}, {Key:"Subject",Value:"English"}, ]; 

$.each(array, function() { 
     if(this.Key === "Subject"){ 
        this.Value = "something" 
     } 
}); 

console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



回答3:


var array=[
        {Key:"Name",Value:"Sam" },
        {Key:"Marks",Value:"50"},
        {Key:"Subject",Value:"English"},
    ];
var i=0;
var value;
for(array as value) {
    value[i]=$(this).text();
    i++;
    alert(value[i]);
}

Try this with key and value



来源:https://stackoverflow.com/questions/41461762/get-value-from-key-value-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!