最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting a value of a certain JSON object field - Stack Overflow

programmeradmin1浏览0评论

I have the following JSON object:

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

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 "pany":

$(".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 definitionsObject object 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".

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

Thank you beforehand.

I have the following JSON object:

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

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 "pany":

$(".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 definitionsObject object 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".

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

Thank you beforehand.

Share Improve this question asked Jul 30, 2012 at 19:27 cycerocycero 4,77120 gold badges59 silver badges81 bronze badges 1
  • 2 That's an object literal, not a "JSON object". – Šime Vidas Commented Jul 30, 2012 at 19:32
Add a ment  | 

2 Answers 2

Reset to default 4

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

definitionsObject.hintID does not return definitionsObject[hintId], it will return definitionsObject['hintId'].

I belive you can acplish this with

var hintText = definitionsObject[hintId];

instead of

var hintText = definitionsObject.hintID;
发布评论

评论列表(0)

  1. 暂无评论