How to get "value" using "key" from json in Javascript / JQuery
Wow ... Looks kind of cool! It looks like you need to manipulate it a bit. Instead of functions, we can create a new object like this:
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
source to share
Since you have an array in your variable, you need to Key
loop over the array and compare with the -Property of each element, something like 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 is a jsonstring
little misleading. It does not contain a string. It contains an array. However, the above code should give you a hint in the right direction.
source to share
Personally, I would create a map from an array, and then it acts like a dictionary giving you instant access. You also only need to go 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]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See the js fiddle here: http://jsfiddle.net/t2vrn1pq/1/
source to share