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

javascript - Accessing a JSON property (String) using a variable - Stack Overflow

programmeradmin8浏览0评论

I'm trying to access a JSON using a variable I'm passing through a function:

function highlightCategory (category) {
   for (var i in data) {
      console.log(data[i].category)
   }
}

Obviously, this doesn't work, because 'category' is what I'm passing with the function and not the real name of the property, but I've been trying different possibilities unsuccessfully. Thanks in advance!

I'm trying to access a JSON using a variable I'm passing through a function:

function highlightCategory (category) {
   for (var i in data) {
      console.log(data[i].category)
   }
}

Obviously, this doesn't work, because 'category' is what I'm passing with the function and not the real name of the property, but I've been trying different possibilities unsuccessfully. Thanks in advance!

Share Improve this question asked Oct 10, 2013 at 15:36 Chiqui EstebanChiqui Esteban 4213 gold badges6 silver badges12 bronze badges 4
  • If category is a string containing the key of the JSON property, it'd be as easy as console.log(data[category]) – devnull69 Commented Oct 10, 2013 at 15:37
  • 1 It'd help if you showed your JSON ... is "category" a direct property of data or is it a sub-property of one of the direct properties? – devnull69 Commented Oct 10, 2013 at 15:40
  • Note: That's not JSON, that is a Javascript object. JSON is a text format to represent objects. – Guffa Commented Oct 14, 2014 at 23:10
  • Does this answer your question? Dynamically access object property using variable – Ivar Commented Feb 21, 2021 at 0:53
Add a ment  | 

1 Answer 1

Reset to default 23
data[i][category]

in JS, obj.prop is synonymous with obj['prop'].

var foo = {
  bar: 'baz'
};
// foo.bar == foo['bar'] == 'baz'

Also, you're dealing with a javascript object, not JSON (though it may have originated there)

Update for those ing across this and using ES6, you can now use variables during assignment:

const propName = 'bar';
const foo = {
  [propName]: 'baz',
}
// foo.bar == foo[propName] == 'baz'

For reference, this is considered a ComputedPropertyName under Object Initializer section of ES6 spec.

发布评论

评论列表(0)

  1. 暂无评论