1

Building on this angular recursive extend topic.

I have slightly modified the version...

var extendDeep = function(dst) {
    angular.forEach(arguments, function(obj) {
        if (obj !== dst) {
            angular.forEach(obj, function(value, key) {
                if (dst[key] && angular.isObject(dst[key])) {
                    extendDeep(dst[key], value);
                } else if(!angular.isFunction(dst[key])) {
                    dst[key] = value;
                }
            });
        }
    });
    return dst;
};

but found that it does not account for arrays correctly. For example, if I have a object like:

var obj = { zoo: [ 'moose', 'panda' ] };

and then I call like:

 deepExtend(obj, {
     zoo: [ 'panda' ]
 })

at first glance you would expect it to remove the object, however, it actually ends up like:

{  zoo: [ 'panda', 'panda' ] }

now. The expected output would look like:

{  zoo: [ 'panda' ] }

This is a very simple case of course.

I'm not really looking for a 'unique' or a 'merge' like most solutions talk about. I need to add items that are missing from the left, remove items that are on the left but not on the right, and then iterate recursively and extend those objects in place.

There are many different ways to go about this, looking for feedback on a good approach.

Community
  • 1
  • 1
amcdnl
  • 8,470
  • 12
  • 63
  • 99
  • What do you want the result to be? What do you mean by "remove the object"? – Bergi Dec 17 '14 at 20:37
  • Notice that arrays are just objects as well. And they're detected by `angular.isObject`, so the key `0` is just updated with the new value – Bergi Dec 17 '14 at 20:37
  • @Bergi added some clarification. yup, i know the isObject will count it like that, in my tests im doing a isArray before that case. – amcdnl Dec 17 '14 at 20:50
  • What you are looking for sounds like the [*symmetric difference*](http://en.wikipedia.org/wiki/Symmetric_difference). However, I don't get how you would need to recursively extend them, as the objects in the result array have no counterpart anywhere? – Bergi Dec 17 '14 at 20:59
  • Also, do you really need your function to work with multiple arguments? Especially that symmetric difference looks a bit ill-defined for that. – Bergi Dec 17 '14 at 21:01
  • You write "there are many different ways" - may you want to show us your approach(es), please? – Bergi Dec 17 '14 at 21:02
  • I just extended the method originally, it accepted multiples, I'm not using that anywhere. – amcdnl Dec 17 '14 at 21:45
  • Can you please [edit] to show us how you extended the method? – Bergi Dec 17 '14 at 21:50

0 Answers0