How to copy javascript object to another object?

Let's say I want to start with an empty 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 this array into an object so that I can use me.nameto return Josh K.

I tried:

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

But this did not have the desired result. Is it possible? My main goal is to wrap this array in a JavaScript object so that I can pass it to a PHP script (via AJAX or something else) as JSON.

+3
source share
8 answers

Since the property name is also a variable, the loop should look like this:

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

To learn more about JSON, you can find this article .

+6

me.i. , , :

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

- , ,

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

, , .

+1

json_encode() .

0

-, "me_arr" , , .

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

, :

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

:

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

, , . : , var!!

0

You should check JSON in JavaScript . There is a JSON library download that can help you create JSON objects.

0
source

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 on "associative arrays in JS" .

0
source

Source: https://habr.com/ru/post/1744960/


All Articles