I have a very large Javascript Object, with a section that is blank, ready for me to dynamically add data to it. For the purpose of this question, I have removed unnecessary parts of my object.
This is my object:
var simplemaps_worldmap_mapdata = {
locations:{
}
}
This is my attempt to insert data into the object:
var mainObj = simplemaps_worldmap_mapdata;
var newObj = [];
newObj.push({
name: 'newName',
lat: 'newLat',
lng: 'newLong',
color: 'newColor',
description: 'newDesc',
url: 'newUrl',
size: 'newSize',
type: 'newType',
opacity: 'newOpacity'
});
mainObj.locations.push(newObj);
DEMO HERE
Why can't I dynamically add data to my object?
EDIT:
This is an example of how locations
should look with one entry:
locations:{
0: {
name: 'newName',
lat: 'newLat',
lng: 'newLong',
color: 'newColor',
description: 'newDesc',
url: 'newUrl',
size: 'newSize',
type: 'newType',
opacity: 'newOpacity'
},
},
The location property is being initialized as object not as an array. Try this:
var simplemaps_worldmap_mapdata = {
locations:[]
}
From your Edited Version you could also try something like:
Array.prototype.push.call(mainObj.locations, newObj);
If its possible to alter your JSON its better to change location
attribute to an array
JSON structure
var simplemaps_worldmap_mapdata = {
locations: []
};
Code
var mainObj = simplemaps_worldmap_mapdata;
var newObj = {
name: 'newName',
lat: 'newLat',
lng: 'newLong',
color: 'newColor',
description: 'newDesc',
url: 'newUrl',
size: 'newSize',
type: 'newType',
opacity: 'newOpacity'
};
mainObj.locations.push(newObj);
JSFiddle
Update
Hope this fixes your issue
JSON structure
var simplemaps_worldmap_mapdata = {
locations: {}
};
Code
var mainObj = simplemaps_worldmap_mapdata;
var newObj = {
name: 'newName',
lat: 'newLat',
lng: 'newLong',
color: 'newColor',
description: 'newDesc',
url: 'newUrl',
size: 'newSize',
type: 'newType',
opacity: 'newOpacity'
};
//Code to find no of keys
if (!Object.keys) {
Object.keys = function (obj) {
var keys = [],
k;
for (k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
keys.push(k);
}
}
return keys;
};
}
var len = Object.keys(mainObj.locations).length;
mainObj.locations[len]= newObj;
Result
{
"locations": {
"0": {
"name": "newName",
"lat": "newLat",
"lng": "newLong",
"color": "newColor",
"description": "newDesc",
"url": "newUrl",
"size": "newSize",
"type": "newType",
"opacity": "newOpacity"
}
}
}
JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With