我有一个很大的Javascript对象,该部分的空白是空白的,可以随时向其中动态添加数据。出于这个问题的目的,我删除了对象的不必要部分。
这是我的对象:
var simplemaps_worldmap_mapdata = {
locations:{
}
}
这是我向对象中插入数据的尝试:
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);
为什么不能将数据动态添加到对象?
编辑:
这是locations
一个条目外观的示例:
locations:{
0: {
name: 'newName',
lat: 'newLat',
lng: 'newLong',
color: 'newColor',
description: 'newDesc',
url: 'newUrl',
size: 'newSize',
type: 'newType',
opacity: 'newOpacity'
},
},
如果可以更改JSON,最好将location
属性更改为数组
JSON结构
var simplemaps_worldmap_mapdata = {
locations: []
};
码
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);
更新资料
希望这能解决您的问题
JSON结构
var simplemaps_worldmap_mapdata = {
locations: {}
};
码
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;
结果
{
"locations": {
"0": {
"name": "newName",
"lat": "newLat",
"lng": "newLong",
"color": "newColor",
"description": "newDesc",
"url": "newUrl",
"size": "newSize",
"type": "newType",
"opacity": "newOpacity"
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句