[英]How to get the 'Value' using 'Key' from json in Javascript/Jquery
I have the following Json string. 我有以下Json字符串。 I want to get the 'Value' using 'Key', something like
我希望使用'Key'得到'Value',就像这样
giving 'BtchGotAdjust' returns 'Batch Got Adjusted'; 给'BtchGotAdjust'返回'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
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
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: 由于变量中有数组,因此必须循环遍历数组并与每个元素的
Key
-Property进行比较,这与以下内容类似:
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. 顺便说一下,我认为你的变量名称
jsonstring
有点误导。 It does not contain a string. 它不包含一个字符串。 It contains an array.
它包含一个数组。 Still, the above code should give you a hint in the right direction.
不过,上面的代码应该会给你一个正确方向的提示。
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]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/ 请参阅js fiddle: http : //jsfiddle.net/t2vrn1pq/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.