I have a controller like this:
CheckoutController = function() {
$scope.Profile = {
firstname : 'Ruchir',
middlename : 'Shakun',
lastname : 'Gupta',
email : '[email protected]',
cellphone : '9876543210'
}
$scope.BillingDetails = {
firstname : undefined,
middlename : undefined,
lastname : undefined,
addressline : undefined,
city : undefined,
zipcode : undefined
}
$scope.update = function() {
// I want to write some awesome code here as explained below
}
}
Now, in the $scope.update
function; I want to write something that should copy 'only common properties' i.e. firstname
, middlename
, and lastname
from $scope.Profile
to $scope.BillingDetails
.
I tried angular.copy
and angular.extend
but,
angular.extend
merges $scope.BillingDetails
and $scope.Profile
.
So I get email
and cellphone
properties in $scope.BillingDetails
as
well -- what I don't want.
angular.copy
overwrites
$scope.BillingDetails
and I lose addressline
, city
and
zipcode
from $scope.BillingDetails
-- what I don't want.
What I want my update
function to do is it should make $scope.BillingDetails
equal to below object:
{
firstname : 'Ruchir',
middlename : 'Shakun',
lastname : 'Gupta',
addressline : undefined,
city : undefined,
zipcode : undefined
}
This scenario is just an example. To shorten the length of my question, I have mentioned 5-6 properties only. In fact, I have to deal with more than 20 properties and all are dynamic. So it won't work for me by copying one-by-one properties firstname
, middlename
and lastname
from Profile
to BillingDetails
.
What can I do?
You may have luck with something like this:
$scope.update = function() {
_update($scope.Profile, $scope.BillingDetails);
}
function _update(srcObj, destObj) {
for (var key in destObj) {
if(destObj.hasOwnProperty(key) && srcObj.hasOwnProperty(key)) {
destObj[key] = srcObj[key];
}
}
}