这是我的代码
angular.forEach(ingredientType, function(index){
var ingredientTypeId = index;
angular.forEach($scope.ingredientList, function(element){
if(ingredientTypeId == element.ingredientTypeId)
{
console.log(ingredientTypeId.toString());
var str = '"' + ingredientTypeId + '"';
var firstElement = {str: element._id};
var secondElement = {str : element.ingredientName};
$scope.itemsToAdd[ingredientTypeId] = {"ingredientId": firstElement, "ingredientName" : secondElement};
}
})
});
预期产出:
[{
"5804b94790b0a11fc2aecef4": [{
"ingredientId": {"5804b94790b0a11fc2aecef4": "580b37f9a67d1e1c45397034"},
"ingredientName": {
"5804b94790b0a11fc2aecef4": "small"
},
"ingredientPrice": "",
"isDuplicate": false
}, {
"ingredientId": "580b37f9a67d1e1c45397123",
"ingredientName": {
"5804b94790b0a11fc2aecef4": "yyui"
},
"ingredientPrice": ""
}],
"5804ba2e90b0a11fc2aecef7": [{
"ingredientId": "580b37f9a67d1e1c45397456",
"ingredientName": {
"5804ba2e90b0a11fc2aecef7": "sdsdsd"
},
"ingredientPrice": ""
}]
}]
我得到的是什么:
= [{
"5804b94790b0a11fc2aecef4": [{
"ingredientId": {ingredientTypeId: "580b37f9a67d1e1c45397034"},
"ingredientName": {
ingredientTypeId: "small"
},
}, {
"ingredientId": {ingredientTypeId : "580b37f9a67d1e1c45397123"},
"ingredientName": {
ingredientTypeId: "yyui"
}
}],
"5804ba2e90b0a11fc2aecef7": [{
"ingredientId": {ingredientTypeId: "580b37f9a67d1e1c45397456"},
"ingredientName": {
ingredientTypeId: "sdsdsd"
}
}]
}];
当我将ingredientTypeId变量放在内部for循环中而不是放置变量的值时,它将替换为变量的名称。
还分享了我的plukr