How to merge objects using javascript? -
i have below
$scope.marketing = [{ 'productid':1, 'productname':'product 1', 'productdescription':'product description 1' }, { 'productid':2, 'productname':'product 2', 'productdescription':'product description 2' }]; $scope.finance=[{ 'productid':1, 'price':'$200.00' }, { 'productid':2, 'price':'$100.00' }]; $scope.inventory=[{ 'productid':1, 'stockinhand:':26 }, { 'productid':2, 'stockinhand':40 }];
i want output
my merge function here
$scope.tempresult=merge($scope.marketing,$scope.finance); $scope.result=merge($scope.tempresult,$scope.inventory); function merge(obj1,obj2){ // our merge function var result = {}; // return result for(var in obj1){ // every property in obj1 if((i in obj2) && (typeof obj1[i] === "object") && (i !== null)){ result[i] = merge(obj1[i],obj2[i]); // if it's object, merge }else{ result[i] = obj1[i]; // add result } } for(i in obj2){ // add remaining properties object 2 if(i in result){ //conflict continue; } result[i] = obj2[i]; } return result;
}
but output
the value first stock in hand missing. please help
what mistake making?
i more glad if helps me in figuring out wrong doing in function. tired. in advance
edit
you use jquery.extend property, have @ plnkr code
$scope.result=merge($scope.marketing, $scope.finance,$scope.inventory); function merge(obj1,obj2, obj3){ return $.extend(true, obj1,obj2,obj3) } };
Comments
Post a Comment