开发者

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.


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.


You may be looking for something as simple as json_encode

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


In your code above, you are setting the me.i property over and over again. To do what you are describing here, try this:

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


Easiest way to truly clone an object without worrying about references is

var newObj = JSON.parse(JSON.stringify(oldObj));

Very convenient, but not viable if you have functions in your objects.


First, "me_arr" shouldn't be an Array, since you're not actually using it like one.

var me_arr = {};
me_arr.name = "Josh K";
me_arr.firstname = "Josh";

Or, shorter:

var me_arr = { "name": "Josh K", "firstname": "Josh" };

Now, your loop is almost right:

for (var key in me_arr) {
  if (me_arr.hasOwnProperty(key))
    me[key] = me_arr[key];
}

I'm not sure what the point is of having two variables in the first place, but whatever. Also: make sure you declare variables with var!!


You should check out JSON in JavaScript. There is a download of a JSON library, that can help you build your JSON objects.


Why don't you just do:

me['name'] = "Josh K";
me['firstname'] = "Josh";

?
This is the same as

me.name = "Josh K";
me.firstname = "Josh";

Read this interesting article about "associative arrays in JS".


Use json_encode() on the finished array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜