Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy a JavaScript object into another object?

Say I want to start with a blank JavaScript object:

me = {};

And then I have an array:

me_arr = new Array();
me_arr['name'] = "Josh K";
me_arr['firstname'] = "Josh";

Now I want to throw that array into the object so I can use me.name to return Josh K.

I tried:

for(var i in me_arr)
{
    me.i = me_arr[i];
}

But this didn't have the desired result. Is this possible? My main goal is to wrap this array in a JavaScript object so I can pass it to a PHP script (via AJAX or whatever) as JSON.

like image 693
Josh K Avatar asked Jul 20 '26 01:07

Josh K


2 Answers

Since the property name is a variable as well, the loop should look like:

for(var i in me_arr)
{
    me[i] = me_arr[i];
}

To learn more about JSON, you may find this article useful.

like image 151
BalusC Avatar answered Jul 22 '26 15:07

BalusC


You may be looking for something as simple as json_encode

http://php.net/manual/en/function.json-encode.php

like image 32
gurun8 Avatar answered Jul 22 '26 15:07

gurun8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!