3

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.

2
  • So all this sample code is in JS, right? Not PHP? In which case php's json_encode won't help you. Commented May 11, 2010 at 15:33
  • The PHP tag is actually irrelevant here. It's just a view/template technology. Writing JS code in a PHP file and having problems with JS doesn't make it a PHP problem :) Commented May 11, 2010 at 15:35

8 Answers 8

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You may be looking for something as simple as json_encode

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

Comments

1

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];
}

Comments

1

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.

1 Comment

if you have functions in your object you will lose them with a stringify
0

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

Comments

0

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

Comments

0

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

Comments

0

Use json_encode() on the finished array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.