" + val.lang...">

The first Json object is *, how to get it?

If I run:

$("#results ul").append(data.parse.langlinks.map(function(val){ return "<li>" + val.lang + "</li>" }));

      

I am getting all the correct values lang

, but I need to get the first object and it has no verbal name, but it does

*

So when I try to access it like val.*

I get:

Uncaught SyntaxError: Unexpected token *

JsFiddle

+3


source to share


3 answers


Access to your project as follows: val['*']

.



+3


source


When accessing objects containing special characters, you need to use parenthesis notation:

return val['*'] + "</li>";

      

https://jsfiddle.net/ryanpcmcquen/fg395Lp9/

It's also worth noting that when accessing an object using a variable or a reserved keyword, you need to use parenthesis notation (thanks @DarthJDG for pointing this out):



var foo = '*';
return val[foo];

      

Also, if you're learning some new aspects of JavaScript, computed property names include parenthesis notation:

https://ryanpcmcquen.org/javascript/2016/10/25/computed-property-names-are-awesome.html

+2


source


My answer is the same as others, but with a little more explanation ...

val["*"]  // Bracket notation

      

Objects in JavaScript really aren't much more than dictionaries, groupings of key / value pairs, or, in other words, associative arrays.

This way you can always access the property of the object (key aka) by passing the string as the index for the object. But if the name index / key / property does not contain illegal characters, then you can use the more general "dot notation".

With that in mind, most people would probably say that the name of an object's property cannot contain spaces, because of course that won't compile and doesn't seem to make any sense:

 obj.some property name = "10";    // won't compile

      

But you can actually have a property name that contains spaces if you think of the object as an array and the property name as a key:

 obj["some property name"] = 10;  // perfectly fine

      

It also opens up great possibilities for dynamic code, as it allows you to dynamically pass a key (string):

var keyName = new Date().toLocaleTimeString();
    
var obj = {};
obj[keyName] = "some value";
     
for(var prop in obj){ 
     console.log("The obj." + prop + " property has a value of: " + obj[prop]);
}
      

Run codeHide result


+1


source







All Articles