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.

8
  • What do you want the result to be? What do you mean by "remove the object"? Commented Dec 17, 2014 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 Commented Dec 17, 2014 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. Commented Dec 17, 2014 at 20:50
  • What you are looking for sounds like the 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? Commented Dec 17, 2014 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. Commented Dec 17, 2014 at 21:01

0

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.