1

I have two objects

$scope.a= {"Sedan":{"Audi":["A3","A4"]},"Hatchback":{"Maruthi":["Swift"]}}; 
var b= {"Hatchback":{"Volkswagen":["Polo"],"Fiat":["Punto1"]}};

I need the following result after merging

{"Sedan":{"Audi":["A3","A4"]},"Hatchback":{"Maruthi":["Swift"],"Volkswagen":["Polo"],"Fiat":["Punto1"]}};
1
  • If you're using lodash, _.merge will suit your needs. Commented Oct 30, 2015 at 7:50

4 Answers 4

3

You can do like this..

$scope.a= {"Sedan":{"Audi":["A3","A4"]},"Hatchback":{"Maruthi":["Swift"]}}; 
var b= {"Hatchback":{"Volkswagen":["Polo"],"Fiat":["Punto1"]}};

 var mergedobj= angular.merge($scope.a, b); //merge object b into $scope.a

see working plunkr here http://plnkr.co/edit/VpHwERUmLqx6MlwQj6JB?p=preview

Sign up to request clarification or add additional context in comments.

1 Comment

If $scope.a= {"Sedan":{"Audi":["A3","A4"]},"Hatchback":{"Maruthi":["Swift"]}}; and var b = var b= {"Hatchback":{"Volkswagen":["Polo"],"Fiat":["Punto1"]}}; I am expecting this: {"Sedan":{"Audi":["A3","A4"]},"Hatchback":{"Maruthi":["Swift"],"Volkswagen":["Po‌​lo"],"Fiat":["Punto1"]}}
1

Use angular.merge

  $scope.object = angular.merge($scope.a, b)

4 Comments

Thanks for your fiddle. If $scope.a= {"Sedan":{"Audi":["A3","A4"]},"Hatchback":{"Maruthi":["Swift"]}}; it is not giving the desired output in this case.
If $scope.a= {"Sedan":{"Audi":["A3","A4"]},"Hatchback":{"Maruthi":["Swift"]}}; and var b = var b= {"Hatchback":{"Volkswagen":["Polo"],"Fiat":["Punto1"]}}; I am expecting this: {"Sedan":{"Audi":["A3","A4"]},"Hatchback":{"Maruthi":["Swift"],"Volkswagen":["Polo"],"Fiat":["Punto1"]}}
any idea regarding this?
use angular.merge($scope.a,b)
0

Try below snippet

$scope.extend(obj, src) {
    for (var key in src) {
       if (src.hasOwnProperty(key)) obj[key] = src[key];
    }
    return obj;
}

To merge the objects

$scope.extend($scope.a, b); 

Or you can use direct jQuery function. Please make sure you should have loaded the jquery min prior to your angular min js. After loading jquery min on the DOM, please call below jQuery function

var newObj = $.extend(true, $scope.a, b); 

Comments

-1

If you need a new object as a result try this:

 var c = {};
 angular.extend(c, $scope.a, b);

or you can do this:

 angular.extend($scope.a, b);

$scope.a will contain the merged result.

2 Comments

It is giving back the object $scope.a
Please see the updated question... sorry for the late edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.