我尝试创建一个新的动态数组。我将一个动态变量值分配给另一个新变量并推送新数组。但是更新了最后一个数组变量值。
for(let i=0;i<allItems.length;i++){
let categories = allItems[i].categories;
for(let j=0;j<categories.length;j++){
let categoryId = categories[j].id;
//console.log("categories[j].id ", categoryId);
allItems[i]['categoryId'] = categoryId;
reitems.push(allItems[i]);
}
}
[{
"itemName" : "3 SS Finish Baskets",
"itemDesc" : "3 SS Finish Baskets",
"itemId" : 1,
"unitId" : 2,
"categories" : [
{
"id" : 1,
"text" : "single room"
},
{
"id" : 2,
"text" : "Foyer/Living"
}
]
},
{
....
}]
[{
"itemName" : "3 SS Finish Baskets",
"categoryId " : 2
},
{
"itemName" : "3 SS Finish Baskets",
"categoryId " : 2
}]
[{
"itemName" : "3 SS Finish Baskets",
"categoryId " 1
},
{
"itemName" : "3 SS Finish Baskets",
"categoryId " 2
}]
答案 0 :(得分:1)
试试这段代码,它会起作用。
{{1}}
答案 1 :(得分:0)
浅拷贝的问题,它是指定数组的引用。
使用angular.copy(源,目标)进行深层复制。
var allItems = [{
"itemName" : "3 SS Finish Baskets",
"itemDesc" : "3 SS Finish Baskets",
"itemId" : 1,
"unitId" : 2,
"categories" : [
{
"id" : 1,
"text" : "single room"
},
{
"id" : 2,
"text" : "Foyer/Living"
}
]
}]
$scope.reitems = [];
for(let i=0;i<allItems.length;i++){
let categories = allItems[i].categories;
for(let j=0;j<categories.length;j++){
let temp = {};
angular.copy(allItems[i], temp);
temp['categoryId'] = categories[j].id;
$scope.reitems.push(temp);
}
}