可能重复:
How can I merge properties of two JavaScript objects dynamically?
我正在尝试在jQuery中合并两个对象。
第一个对象:
var rules1 = {
firstname: { required: true, minlength: 3 },
lastname: { required: true, minlength: 3 }
};
第二个对象:
var rules2 = {
test1: { required: true, minlength: 3 },
test2: { required: true, minlength: 3 }
};
我希望结果看起来像这样:
var merged = {
firstname: { required: true, minlength: 3 },
lastname: { required: true, minlength: 3 },
test1: { required: true, minlength: 3 },
test2: { required: true, minlength: 3 }
};
我还需要知道rules1
的PHP数组看起来如何,因为此对象将使用json_encode
函数进行转换。
答案 0 :(得分:0)
您可以合并它们:
var merged = $.extend(rules1, rules2);
如果你想从php构建它,你的对象将是:
$rules = new stdClass;
$rules->test1 = new stdClass;
$rules->test1->required = true;
....
就个人而言,在PHP中,我更喜欢使用数组。然后可以使用一些自定义函数将它们转换为stdClass recursevely。你可以在这里找到其中一个:
http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass