繁体   English   中英

如何在Javascript / Jquery中使用json中的'Key'获取'Value'

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

我有以下Json字符串。 我希望使用'Key'得到'Value',就像这样

给'BtchGotAdjust'返回'Batch Got Adjusted';

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

哇...看起来有点难! 好像你需要稍微操纵一下。 我们可以用这种方式创建一个新对象,而不是函数:

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"];

您可以使用它:

finalJSON["BtchGotAdjust"]; // Batch Got Adjusted

由于变量中有数组,因此必须循环遍历数组并与每个元素的Key -Property进行比较,这与以下内容类似:

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

顺便说一下,我认为你的变量名称jsonstring有点误导。 包含一个字符串。 它包含一个数组。 不过,上面的代码应该会给你一个正确方向的提示。

我个人会从数组创建一个地图,然后它就像一个字典,让你即时访问。 您还必须遍历数组一次以获取所需的所有数据:

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)

请参阅js fiddle: http//jsfiddle.net/t2vrn1pq/1/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM