hackerman90219
hackerman90219

Reputation: 81

Accessing object property via key in JavaScript

Doing a project currently using Knockout.JS as my MVVM framework. I'm trying some basic operations such as accessing the values of my particular markersArray object using something simple such as markersArray['Tiong Bahru Station (EWL)']. I understand that I have to use square bracket notation due to the presence of spaces. However, when I console.log this, and further in my code, it has no value.

Code is below:

JS

In scripts.js file:

var stationList = [
        {name: "Tiong Bahru Station (EWL)", marker: markersArray['Tiong Bahru 
Station (EWL)']}
console.log(markersArray['Tiong Bahru Station (EWL)']); // Returns undefined


In maps.js file:

var markersArray = {};
for (var i = 0; i < markers.length; i ++) {
    marker = new google.maps.Marker({
        position: markers[i].position,
        map: map,
        animation: google.maps.Animation.DROP
    });
    var name = markers[i].name;
    markersArray[name] = marker;
}
var markers = [
{name:"Tiong Bahru Station (EWL)", position: {lat:1.28498, lng:103.82283}}
];

I went to check the console.log for my markersArray to ensure that it is built correctly and it is populated correctly. Would appreciate some help in figuring out why I'm not getting any value from just accessing the value using the key.

Upvotes: 0

Views: 35

Answers (2)

hackerman90219
hackerman90219

Reputation: 81

I added an "async" keyword to the script I was loading and that solved the problem. It's because I was waiting for the entire document to load before running the script below it, which caused some issues.

Upvotes: 0

user3094755
user3094755

Reputation: 1641

This snippet sort of works, but I'm not sure what the problem you have is.

The simplest solution would be to put your marker into the makers Array, and then point to the markers Array, with

markers[i].marker = 'The Marker' markers[markers[i].name] = markers[i]

var markers = [
{name:"Tiong Bahru Station (EWL)", position: {lat:1.28498, lng:103.82283}}
];

var markersArray = {};
for (var i = 0; i < markers.length; i ++) {
    var name = markers[i].name;
    markersArray[name] = 'The marker';
}

console.log(JSON.stringify(markers,null,2))

console.log(JSON.stringify(markersArray,null,2))

Upvotes: 1

Related Questions