我有一个非常大的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'
},
},
答案 0 :(得分:6)
正在初始化location属性作为对象而不是数组。试试这个:
var simplemaps_worldmap_mapdata = {
locations:[]
}
从已编辑的版本中,您还可以尝试以下内容:
Array.prototype.push.call(mainObj.locations, newObj);
答案 1 :(得分:3)
如果可以更改您的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"
}
}
}
答案 2 :(得分:1)
对于多个locations
:
var simplemaps_worldmap_mapdata = {
locations: []
}
var newObj = {
name: 'newName',
lat: 'newLat',
lng: 'newLong',
color: 'newColor',
description: 'newDesc',
url: 'newUrl',
size: 'newSize',
type: 'newType',
opacity: 'newOpacity'
};
var mainObj = simplemaps_worldmap_mapdata;
mainObj.locations.push(newObj);
console.log(mainObj);