0

Possible Duplicate:
How can I merge properties of two JavaScript objects dynamically?

I am trying to merge two objects in jQuery.

first object:

var rules1 = {  
    firstname: { required: true, minlength: 3 },
    lastname: { required: true, minlength: 3 }
};

second object:

var rules2 = {  
    test1: { required: true, minlength: 3 },
    test2: { required: true, minlength: 3 }
};

I want the result to look like this:

var merged = {  
    firstname: { required: true, minlength: 3 },
    lastname: { required: true, minlength: 3 },
    test1: { required: true, minlength: 3 },
    test2: { required: true, minlength: 3 }
};

I also need to know how might look like the PHP array for rules1, because this object will be tranformed with json_encode function.

Community
  • 1
  • 1
  • 1
    These are objects, not arrays. In PHP you just create an associative array: `$arr = array('firstname' => array('required': true, ...))`. Read more about arrays in PHP: http://php.net/manual/en/language.types.array.php – Felix Kling Oct 12 '12 at 08:33

1 Answers1

0

You can merge them doing this:

var merged =  $.extend(rules1, rules2);

If you want build it from php your object will be:

$rules = new stdClass;
$rules->test1 = new stdClass;
$rules->test1->required = true;
....

Personally, in PHP I prefer to work with arrays. Then they can be converted to stdClass recursevely by using some custom functions. You can find one of these here:

http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass

Stefano Ortisi
  • 5,288
  • 3
  • 33
  • 41