Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the 'Value' using 'Key' from json in Javascript/Jquery

I have the following Json string. I want to get the 'Value' using 'Key', something like

giving 'BtchGotAdjust' returns 'Batch Got Adjusted';

var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
like image 888
Vivek Ranjan Avatar asked Jan 10 '23 23:01

Vivek Ranjan


2 Answers

Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:

var jsonstring =
    [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
     var finalJSON = {};
     for (var i in jsonstring)
         finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];

You can use it using:

finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
like image 143
Praveen Kumar Purushothaman Avatar answered Jan 12 '23 12:01

Praveen Kumar Purushothaman


As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:

for (var i = 0; i < jsonstring.length; i++) {
  if (jsonstring[i].Key === 'BtchGotAdjust') {
    console.log(jsonstring[i].Value);
  }
}

By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.

like image 41
Dennis Avatar answered Jan 12 '23 11:01

Dennis