Reputation:
I want to make an object using angular.forEach()
function and then I need to push another object and initialize all the values to false but the below way points errors.
How can do this correctly? if I use "item.id" and "index.id" it will not create the intended functionality. I am attaching a photo to point out the intended functionality.link for image
angular.forEach(metaData.validationRules, function (item, key) {
//want to push object to another object
angular.forEach(insarray.instances, function (index, key) {
$scope.select = {
item.id: {
index.id:false
}
}
});
});
Upvotes: 1
Views: 589
Reputation: 56
The problem is that it's not possible to set the key of a key-value-pair the way you do it in your example. A better approach would be:
$scope.select = {};
angular.forEach(metaData.validationRules, function (item, key) {
$scope.select[item.id] = $scope.select[item.id] || {};
angular.forEach(insarray.instances, function (index, key) {
$scope.select[item.id][index.id] = false;
});
});
Consider the declaration of the new select object outside of the loops. This is important, otherwise you would overwrite the object on each cycle.
Upvotes: 0
Reputation: 524
It is not available for now but with ES6 you can also use this syntax.
angular.forEach(metaData.validationRules, function (item, key) {
//want to push object to another object
angular.forEach(insarray.instances, function (index, key) {
$scope.select={
[item.id]: {
[index.id]:false
}
}
});
});
Upvotes: 1