如何在 Javascript/Jquery 中使用 json 中的“Key”获取“Value”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25503627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the 'Value' using 'Key' from json in Javascript/Jquery
提问by Vivek Ranjan
I have the following Json string. I want to get the 'Value' using 'Key', something like
我有以下 Json 字符串。我想使用“键”获取“值”,例如
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
给 'BtchGotAdjust' 返回 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
回答by Praveen Kumar Purushothaman
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
回答by Dennis
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. It does notcontain a string. It contains an array. Still, the above code should give you a hint in the right direction.
顺便说一句,我认为你的变量名jsonstring
有点误导。它不包含一个字符串。它包含一个数组。尽管如此,上面的代码应该给你一个正确方向的提示。
回答by Magrangs
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 小提琴:http: //jsfiddle.net/t2vrn1pq/1/