0

I am attempting to create a javascript object so that I can tranfsorm it into a json string in order to update a mysql table via php. I'm new to objects and json in javascript and so I have followed a couple of tutorials on the web but still can't seem to be getting this to work:

var idArray =      [ 1, 2, 3];
var slideNo =      [ 1, 2, 3];
var isPublished =  [ 0, 1, 0];
var floaText =     [ 1, 0 , 1];

var myObject = [];

for(var i = 0; i < idArray.length; i++) {
    myObject[i] = {
        slideId : idArray[i],
        slideNo : slideNo [i],
        isPublished : isPublished [i],
        floatText : floaText [i]
    };
}

alert(myObject[0].slideId);

I can't seem to get the above code work. I also tried to add quoation makrs like this:

myObject[i] = {
    slideId : "\"" + idArray[i] + "\"",
    slideNo : "\"" + slideNo[i] + "\"",
    isPublish : "\"" + isPublished[i] + "\"",
    floatText : "\"" + floaText[i]
};

But that doesn't seem to work either. What am I doing wrong?

2
  • sorry, I did actually have them as [] and not {} for the arrays Commented Apr 30, 2014 at 22:49
  • Based on your example slideArray, publishArray and floatArray don't exist. You have them named slideNo, isPublished, and floaText. Commented Apr 30, 2014 at 22:56

2 Answers 2

2

Looks like your recent edit fixed one of the issues: you need [] around your arrays, not {}.

Next, you need to change your array variable names to match what you're using in your for loop.

Finally, myObject should probably be an array, not an object, so change its {} to [].

Here's an updated version of your code:

var idArray =         [ 1, 2, 3];
var slideArray =      [ 1, 2, 3];
var publishArray =    [ 0, 1, 0];
var floatArray =      [ 1, 0 , 1];

var myObject = [];

for(var i = 0; i < idArray.length; i++) {
    myObject[i] = {
        slideId : idArray[i],
        slideNo : slideArray[i],
        isPublished : publishArray[i],
        floatText : floatArray[i]
    };
}

alert(myObject[0].slideId);
2
  • Thanks, I made those changes (see above code) but it still seems to be failing. In fact, not even the alert box is appearing. Any other suggestions? Commented Apr 30, 2014 at 23:07
  • Anything that's keeping your alert box from appearing is outside of the code you've posted so far. Commented Apr 30, 2014 at 23:49
0

use JSON.stringify to convert object to json string

alert(JSON.stringify(myObject[i]));

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.