我试图创建一个新的动态数组。我将一个动态变量值分配给另一个新变量并推送新数组。但是更新最后一个数组变量值。
法典
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]);
}
}
我的 JSON 值:
[{
"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
}]
试试这段代码,它会起作用。
let allItems = data;
let reitems = [];
let n = 0;
let allItemCategory = data.categories;
for(let i=0; i<allItems.length; i++){
allItems[i].categories.forEach(element => {
console.log('element.id',element.id)
let categoryId = element.id;
var obj = {
categoryId : element.id,
itemName : allItems[i].itemName,
itemDesc : allItems[i].itemDesc
}
reitems[n] = obj;
n++;
});
}
console.log('allI new reitems ------->', reitems);
浅拷贝的问题,它正在分配数组的引用。
使用 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);
}
}