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"},]

asked Jun 3, 2015 in JAVASCRIPT by rajesh
0 votes

2 Answers

0 votes
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:

answered Jun 3, 2015 by rajesh
0 votes
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:

var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]

var map = {}

for (var i=0; i < objectArray.length; i++){
    map[objectArray[i].Key] = objectArray[i]

answered Jun 3, 2015 by rajesh