Reputation: 1435
I have two separate objects which is shown below
Object1 = [{value:'A/B'},{value:'A/B/C'},{value:'A/F'},{value:'A/'}];
Object2 =[{option:'A/'},{option:'A/B'}];
Now i need to modify the Object2 by adding a new attribute so that the Object2 must look like this
Object2 = [{option:'A/',
directories:[{value:'A/'},{value:'A/B'},{value:'A/B/C'},{value:'A/F'}]},
{option:'A/B',
directories:[{value:'A/B'},{value:'A/B/C'},{value:'A/F'},{value:'A/'}]}];
The changes what i need is
In directories attribute the first value should be the option value
Other values should be the remaining values that should come from Object1
I have tried the following code
angular.forEach(Object2,function(value,key){
angular.forEach(Object1,function(value,key){
//I need the code here
});
});
Upvotes: 1
Views: 614
Reputation: 4448
Try the following
angular.forEach($scope.Object2,function(value,key){
value.directories = angular.copy($scope.Object1);
for (var i=0; i < value.directories.length; i++) {
if (value.directories[i].value === value.option) {
var item = value.directories.splice(i,1);
value.directories.unshift(item[0]);
break;
}
}
});
basically after adding the directories array to your object you can find the index of the object that you want in the start of array remove it and add it back to the beginning of the array.
Upvotes: 1
Reputation: 44145
Why are you iterating twice? You can use just one forEach
loop and an arrow function with destructuring:
angular.forEach($scope.Object2, { directories } => directories = $scope.Object1);
Upvotes: 0