-1

My code is like

var param="abc";
var data = {abc:1,xyz:2};//json data
console.log(data.abc);
//console.log(data.param);

Here m accessing data using data.abc, its outcome is 1. But when i tried to pass this "abc " using parameter param its showing undefined.

Here m not not getting weather it is possible to access data using param if yes then how???

can somebody help me on this???

Sumant
  • 954
  • 1
  • 18
  • 39

2 Answers2

5

JSON is simply a serialisation format that uses a text-based subset of JavaScript in a string - using objects in JavaScript isn't JSON (name of it I admit is slightly confusing, to say the least).

To do what you want, simply use the square bracket notation:

console.log(data[param]);

It allows any expression to be placed into it and the return value will be converted into a string, then used to access the property on the object - this allows variables such as param to be used dynamically.

For example, here are some results which occur when you're using the square bracket notation:

var foo =
    { '[object Object]': 1
    , bar: 2 };
var x = "bar";

foo[{}]; // 1
foo['[object Object]']; // 1
foo.[object Object]; // SyntaxError: Unexpected token [
foo[bar]; // ReferenceError: bar is not defined
foo.bar; // 2
foo["bar"]; // 2 
foo[x]; // 2
foo.x; // undefined
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
2

console.log(data[param]); Should do it.

phuzi
  • 12,078
  • 3
  • 26
  • 50