0

我正在尝试将所有数据对象加入一个它们都被链接的地方

var person1 = {
    hello: {
        "david": {
            "hours": "44",
            "money": "22"
        }
    }
};


var person2 = {
    world: {
        "pearce": {
            "hours": "21",
            "money": "11"
        }
    }
};

我希望它看起来像这样:

var mergedObjects = {
    hello: {
        "david": {
            "hours": "44",
            "money": "22"
        }
    },
    world: {
        "pearce": {
            "hours": "21",
            "money": "11"
        }
    }
};

我知道如何使用数组来做到这一点,但是我怎样才能在 javascript 中做到这一点,作为保持正确结构的 JSON 对象

4

3 回答 3

1

看一下这个....

答案就在这里...如何动态合并两个 JavaScript 对象的属性?

JS小提琴

JS:

 function mergeRecursive(obj1, obj2) {

  for (var p in obj2) {
    try {
      // Property in destination object set; update its value.
      if ( obj2[p].constructor==Object ) {
        obj1[p] = mergeRecursive(obj1[p], obj2[p]);

      } else {
        obj1[p] = obj2[p];

      }

    } catch(e) {
      // Property in destination object not set; create it and set its value.
      obj1[p] = obj2[p];

    }
  }

  return obj1;
}

var person1 = {
    hello: {
        "david": {
            "hours": "44",
            "money": "22"
        }
    }
};


var person2 = {
    world: {
        "pearce": {
            "hours": "21",
            "money": "11"
        }
    }
};

console.log(mergeRecursive(person1, person2));
于 2013-11-13T05:40:21.640 回答
0

您可以使用 jQuery 轻松做到这一点:

var person1 = {
    hello: {
        "david": {
            "hours": "44",
            "money": "22"
         }
    }
};


var person2 = {
    world: {
        "pearce": {
            "hours": "21",
            "money": "11"
        }
    }
};

var mergedObjects = $.extend({}, person1, person2);

console.dir(mergedObjects);
于 2013-11-13T06:07:24.000 回答
0

检查这篇文章:链接

var person1 = {
    hello: {
        "david": {
            "hours": "44",
            "money": "22"
        }
    }
};


var person2 = {
    world: {
        "pearce": {
            "hours": "21",
            "money": "11"
        }
    }
};


function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}



merge_options(person1,person2);
于 2013-11-13T05:45:03.850 回答