最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Appending objects to existing objects - Stack Overflow

programmeradmin5浏览0评论

Are there any existing methods to append an object to another object?

I've had a quick stab at throwing this together but I'm not sure about a couple of things:

  • Am I handling methods correctly? I added an exception for append but what about when other prototype functions exist? Should I just ignore functions in the new class?

  • What should I do about null / undefined values?

  • Also, I've just thought about arrays.. what would be the best way to handle arrays? typeof reports as 'object'.. I guess that testing the Array().constructor value would be the way forward

Other than these couple of issues it seems to function as I want it to (overwriting/adding individual parts of the existing object only where it exists in the new object). Are there any edge cases I've missed?

Object.prototype.append = function(_newObj)
{
  if('object' !== typeof _newObj) {
    console.info("ERROR!\nObject.prototype.append = function(_newObj)\n\n_newObj is not an Object!");
  }

  for (newVar in _newObj)
  {
    switch(typeof _newObj[newVar]){
      case "string":
        //Fall-through
      case "boolean":
        //Fall-through
      case "number":
        this[newVar] = _newObj[newVar];
      break;

      case "object":
        this[newVar] = this[newVar] || {};
        this[newVar].append(_newObj[newVar]);
      break;

      case "function":
        if(newVar !== 'append'){
          this[newVar] = _newObj[newVar];
        }
      break;
    }
  }

  return this;

}


var foo = { 1:'a', 2:'b', 3:'c' };
var bar = { z: 26, y: 25, x: 24, w: { 'foo':'bar'}, v: function(){ alert('Hello world"'); } };

foo.append(bar);
console.info(foo);

Are there any existing methods to append an object to another object?

I've had a quick stab at throwing this together but I'm not sure about a couple of things:

  • Am I handling methods correctly? I added an exception for append but what about when other prototype functions exist? Should I just ignore functions in the new class?

  • What should I do about null / undefined values?

  • Also, I've just thought about arrays.. what would be the best way to handle arrays? typeof reports as 'object'.. I guess that testing the Array().constructor value would be the way forward

Other than these couple of issues it seems to function as I want it to (overwriting/adding individual parts of the existing object only where it exists in the new object). Are there any edge cases I've missed?

Object.prototype.append = function(_newObj)
{
  if('object' !== typeof _newObj) {
    console.info("ERROR!\nObject.prototype.append = function(_newObj)\n\n_newObj is not an Object!");
  }

  for (newVar in _newObj)
  {
    switch(typeof _newObj[newVar]){
      case "string":
        //Fall-through
      case "boolean":
        //Fall-through
      case "number":
        this[newVar] = _newObj[newVar];
      break;

      case "object":
        this[newVar] = this[newVar] || {};
        this[newVar].append(_newObj[newVar]);
      break;

      case "function":
        if(newVar !== 'append'){
          this[newVar] = _newObj[newVar];
        }
      break;
    }
  }

  return this;

}


var foo = { 1:'a', 2:'b', 3:'c' };
var bar = { z: 26, y: 25, x: 24, w: { 'foo':'bar'}, v: function(){ alert('Hello world"'); } };

foo.append(bar);
console.info(foo);
Share Improve this question edited Sep 7, 2010 at 19:53 kwah asked Sep 7, 2010 at 18:11 kwahkwah 1,1491 gold badge13 silver badges28 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

You forgot "boolean" as in

typeof true

I like it. I've used a similar, but not as robust method in my code. But it would probably be safer to implement it as a static method for the Object class:

if (typeof Object.merge !== 'function') {
    Object.merge = function(_obj, _newObj)
    {
        if("object" !== typeof _obj)
            console.info("ERROR!\nObject.merge = function(_obj, _newObj)\n\n_obj is not an Object!");
        if("object" !== typeof _newObj)
            console.info("ERROR!\nObject.merge = function(_obj, _newObj)\n\n_newObj is not an Object!");

        for (newVar in _newObj)
        {
            switch(typeof _newObj[newVar]){
                case "object":
                    _obj[newVar] = _obj[newVar] || {};
                    Object.merge(_obj[newVar], _newObj[newVar]);
                    break;
                case "undefined": break;
                default: // This takes care of "string", "number", etc.
                    _obj[newVar] = _newObj[newVar];
                    break;
            }
        }
        return _obj;
    }
}

var foo = { 1:'a', 2:'b', 3:'c' };
var bar = { z: 26, y: 25, x: 24, w: { 'foo':'bar'}, v: function(){ alert('Hello world"'); } };
Object.merge(foo, bar);
console.info(foo);

To answer your questions, I haven't found any better methods (outside of a framework) to do this either. For null/undefined values, you if the _newObj has null/undefined values, then shouldn't your recipient object also have those (i.e. don't make any special case for those)?

Most JS libraries have a method to do this, jQuery has $.extend(dest, src[, src2 ...]), the source code for that method can be found here: http://github./jquery/jquery/blob/116f3b7c72004f3173a7d92457154a1fdb2180e1/src/core.js#L294

发布评论

评论列表(0)

  1. 暂无评论