views:

183

answers:

7

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.

A: 

Use Json_encode on the finished array

Galen
A: 

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!!

Pointy
+4  A: 

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.

BalusC
+1  A: 

You may be looking for something as simple as json_encode

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

gurun8
A: 

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];
}
Jeff Fohl
A: 

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

Zachary
A: 

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".

Felix Kling