Fact Finder
Fact Finder

Reputation: 191

Get Value from Key Value array

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?

Upvotes: 2

Views: 38616

Answers (3)

Devraj Gupta
Devraj Gupta

Reputation: 339

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

Upvotes: 0

Frogger
Frogger

Reputation: 185

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>

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075745

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"
    }
});

Upvotes: 6

Related Questions