我尝试使用for..in循环遍历名称列表,将它们添加到模板对象(' group'),然后将每个完整对象添加到数组中(' queryList&#39)。这不起作用,因为每次迭代都会覆盖数组中的所有值。有什么建议为什么会这样?
// BATTERY OBJECT
var groupList = [ "LOGIN", "BROWSE", "SEARCH"];
// GROUP OBJECT
var group = {dbName: 'CARS', name: '', collectionName: 'group'};
// INIT VARS
var groupName = '',
queryList = [];
// COMPILATION FUNCTION
var buildGroupQueries = function(group){
// BUILD BATCH OF QUERIES
for (var i in groupList){
groupName = groupList[i];
group.name = groupName;
queryList[i] = group;
}
console.log(queryList);
}
buildGroupQueries(group);
应该看起来像:
[
{"dbName":"CARS","name":"LOGIN","collectionName":"group"},
{"dbName":"CARS","name":"BROWSE","collectionName":"group"},
{"dbName":"CARS","name":"SEARCH","collectionName":"group"}
]
相反,我得到了:
[
{"dbName":"CARS","name":"SEARCH","collectionName":"group"},
{"dbName":"CARS","name":"SEARCH","collectionName":"group"},
{"dbName":"CARS","name":"SEARCH","collectionName":"group"}
]
答案 0 :(得分:2)
每次修改group
对象,但需要修改其副本。
在行for (var i in groupList){
var _group = {};
for (var j in group){ _group[j] = group[j]; }
在每次迭代中,您都会创建一个新对象,并从主对象中复制所有属性。
答案 1 :(得分:1)
您正在创建一个引用同一对象的元素数组,因此它们都显示与您上次更改时相同的名称,在您的示例中为“SEARCH”。
您必须将每个元素引用到从您要用作模板的对象创建的新对象中
为此,您可以循环其属性或克隆它,如下所示:
// BATTERY OBJECT
var groupList = [ "LOGIN", "BROWSE", "SEARCH"];
// GROUP OBJECT
var group = {dbName: 'CARS', name: '', collectionName: 'group'};
// INIT VARS
var groupName = '',
queryList = [];
// COMPILATION FUNCTION
var buildGroupQueries = function(group){
var i, _group;
// BUILD BATCH OF QUERIES
for (i in groupList){
_group = JSON.parse(JSON.stringify(group));
groupName = groupList[i];
_group.name = groupName;
queryList[i] = _group;
}
console.log(queryList);
}
buildGroupQueries(group);