Skip to content Skip to sidebar Skip to footer

Create Javascript Object

I have this function // add history paths and save data function AddPath( strTag, strUserName, arrayLatLngPoints, pathColour) { for (var i = 0; i < arrayLatLngPoints.length;

Solution 1:

How can i create this object?

Pretty much exactly like you did:

var obj = { strUserName : { timestamp : point.timestamp , LatLng : point.LatLng }, strUserName : { timestamp : point.timestamp , LatLng : point.LatLng } };

Or more readably:

var obj = {
    strUserName : {
        timestamp : point.timestamp ,
        LatLng : point.LatLng
    },
    strUserName : {
        timestamp : point.timestamp ,
        LatLng : point.LatLng
    }
};

That's an object initializer. It creates a new object with the given properties (actually, three new objects) and returns a reference to the outermost of them.

Taking some simpler examples:

// Create a blank object (an object with no properties of its own):
var a = {};

// Create an object with a `name` property with the value "Fred"
var b = {name: "Fred"};

// Create an object with a `foo` property, which is *another* freshly-created
// object with a `name` property with the value "Barney"
var c = {
    foo: {
        name: "Barney"
    }
};

Re your updated question:

the username has not worked and im not getting an item for each timestamp, its just overwriting the one entry?

Of course it is, you're overwriting history on each loop, without storing the earlier copy anywhere. For instance, you can store them in an array:

// add history paths and save data
function AddPath( strTag, strUserName, arrayLatLngPoints, pathColour) {

  var historyArray = [];
  for (var i = 0; i < arrayLatLngPoints.length; i++)
    {
    var point = arrayLatLngPoints[i];
    var pos = new google.maps.LatLng(point.lat, point.lng);

    historyArray[i] = {
        strUserName : {
            timestamp : point.timestamp ,
            LatLng : pos
        }
    };

    var date = new Date( parseInt( point.timestamp));
    addMarkers(point.timestamp, point.lat, point.lng, point.timestamp, strUserName, pathColour, date.toString());
    date = null; 
    }
console.log(historyArray);
}

Solution 2:

var obj = {strUserName: {timestamp: point.timestamp, lat: point.lat, long: point.long}}

Post a Comment for "Create Javascript Object"