javascript 获取某个 JSON 对象字段的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11728236/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:08:55  来源:igfitidea点击:

Getting a value of a certain JSON object field

javascriptjqueryjson

提问by cycero

I have the following JSON object:

我有以下 JSON 对象:

var definitionsObject = {"company" : "Some information about company"};

This object will actually contain a lot of definitions, not just one. And I also have the following event handler for a link click which has a custom "data-name" attribute containing the term "company":

这个对象实际上会包含很多定义,而不仅仅是一个。而且我还有以下链接点击事件处理程序,它具有包含术语“公司”的自定义“数据名称”属性:

$(".definitinOpener").click(function() {
      $this = $(this);
      var hintID = $this.attr("data-name");
      var hintText = definitionsObject.hintID;
});

So, what I'm trying to do is get the value of "data-name" custom attribute of the clicked link, go to the definitionsObjectobject and get the value of the field which is equal to the "data-name" attribute value. However in this way I'm always getting "undefined".

所以,我想要做的是获取单击链接的“数据名称”自定义属性definitionsObject的值,转到对象并获取等于“数据名称”属性值的字段值。然而,通过这种方式,我总是得到“未定义”。

Could anybody please help me to figure out what exactly I'm doing wrong?

有人可以帮我弄清楚我到底做错了什么吗?

Thank you beforehand.

先谢谢了。

回答by Kristoffer Sall-Storgaard

You can look up a value in an object in two ways.

您可以通过两种方式在对象中查找值。

var obj = { key : 'value' }
var lookup = 'key'

console.log( obj.lookup ) //undefined
console.log( obj.key ) //value
console.log( obj[lookup] ) //value

You probably want this:

你可能想要这个:

var hintText = definitionsObject[hintID];

回答by gbtimmon

definitionsObject.hintIDdoes not return definitionsObject[hintId], it will return definitionsObject['hintId'].

definitionsObject.hintID不返回definitionsObject[hintId],它会返回definitionsObject['hintId']

I belive you can accomplish this with

我相信你可以做到这一点

var hintText = definitionsObject[hintId];

instead of

代替

var hintText = definitionsObject.hintID;