javascript – 修改jQuery扩展以推送对象中的数组项,但扩展其他对象

我认为这一定是一个常见的问题,但似乎无法找到解决方案.
使用 JSON配置文件来扩展包含对象和数组的jQuery对象.

对于对象和简单属性,我想覆盖(因为扩展很好).

对于阵列,可能存在也可能不存在现有项目.

目前,数组只会覆盖第一个元素

var sourceObj = {propterty:"change Me",anArray:[{name:"first"},{name:"second"}]},configJSON = '{"propterty":"New Val","anArray":[{"name":"third"}]}',configObj = JSON.parse(configJSON);

$.extend(true,sourceObj,configObj);

http://jsfiddle.net/PmuwV/

返回:

{propterty:"New Val",anArray:[{name:"third"},{name:"second"}}

我可以改为:

{propterty:"New Val",{name:"second"},{name:"third"}]}

而且还允许更新“第一”和“第二”对象?

"anArray":[{"name":"second","newProp":"add newProp to second"}]

可以/应该扩展修改以比较数组项,并根据某些规则或设置属性值(如“名称”)进行扩展或添加

感谢您的任何建议或指示.

解决方法

我用这个解决方http://jsfiddle.net/PmuwV/2/
从0700年起也从 JavaScript equivalent of jQuery’s extend method修改

需要isDOMNode()
我刚刚在数组中添加一个jquery合并(是的,我也觉得很脏),其中需要在合并后清理重复项.
扩展的Jquery源代码非常相似,但我发现它更具可读性.

function mergeRecursive() {
  // _mergeRecursive does the actual job with two arguments.
  var _mergeRecursive = function (dst,src) {
    if ( isDOMNode(src) || typeof src!=='object' || src===null) {
      return dst; 
    }

    for ( var p in src ) {

//my added bit here - [SB]
      if ($.isArray(src[p])){
          $.merge(dst[p],src[p]);
          var dupes = {},singles = [];
          $.each(  dst[p],function(i,el) {
             if ((dupes[el.name] > -1) &&  (el.name)) {
                 $.extend(singles[dupes[el.name]],el);
             }else{
                  if (el.name ){
                     dupes[el.name] = i;
                  }
                 singles.push(el);
             }
         });
         dst[p] = singles;
         }
         continue;        
      }
//the rest is original - [SB]

      if( !src.hasOwnProperty(p) ) continue;
      if ( src[p]===undefined ) continue;
      if ( typeof src[p]!=='object' || src[p]===null) {
        dst[p] = src[p];
      } else if ( typeof dst[p]!=='object' || dst[p]===null ) {
        dst[p] = _mergeRecursive(src[p].constructor===Array ? [] : {},src[p]); 
      } else {              
        _mergeRecursive(dst[p],src[p]);
      }
    }
    return dst;
  }

  // Loop through arguments and merge them into the first argument. 
  var out = arguments[0];
  if ( typeof out!=='object' || out===null) return out;
  for ( var i=1,il=arguments.length; i<il; i++ ) {
    _mergeRecursive(out,arguments[i]);
  }
  return out;
}

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...