0

How do I parse a particular object value in an array of objects, object attribute having special characters:

var mycars = new Array();

var obj = {"x-h": "4", "y": "1"};

mycars.push(obj);

document.write(mycars[0].a-h + "<br>");
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

2 Answers2

1

Access the property as follows (using quotes):

document.write(mycars[0]["x-h"] + "");

Also note that you were using "a-h" instead of "x-h".

johnnycardy
  • 3,049
  • 1
  • 17
  • 27
0

Values can be retrieved from an object using brackets [ ] .

If your string expression is a legal JavaScript name and not a reserved word, then the "." notation can be used instead.

"x-h" is not a legal Javascript name. Instead you can use x_h , then you can use the "." notation access directly:

document.write(mycars[0].x_h + "");
Alberto Montellano
  • 5,886
  • 7
  • 37
  • 53
  • *"If your string expression is a legal JavaScript name and not a reserved word, then the "." notation can be used instead."* You can even use the dot notation if the property name is a reserved word. Example: `var x = {if: 42}; alert(x.if);`. The problem is that some (especially older) browsers will have a problem with that. – Felix Kling Jan 08 '14 at 20:16
  • Yes, you are right Felix, however it is not a good practice. – Alberto Montellano Jan 08 '14 at 20:58