views:

84

answers:

4

I want to create a new object and assign some properties for each array stored within some json. I have this mostly working except...

for (var i in json) {

            a = 0;
            a++;
            a = new Object();

            for (var key in json[i]) {
                var Key = key;
                var Value = json[i][key];
                a[Key] = Value;
            }
            a.outputProperties();
        }

When I output the object properties, everything is undefined.

If I create a single object outside the loop and assign the properties to it, it seems to work OK except that the first set of properties get overwritten with the following. Not sure why I wouldn't be able to create objects and assign properties inside the loop dynamically.

+2  A: 

You never actually set any properties of a. You just set properties of sup2. On a side note you have other unnecessary stuff in there like var Key = key; Try this:

for (var i in json) {
    var a = new supplement();
    for (var key in json[i]) {
        a[key] = json[i][key];
    }
    a.outputProperties();
}
Dave Aaron Smith
Thank you, this did the trick!
chromaloop
+1  A: 

The code you pasted doesn't look right to me, in the sense of it doesn't seem to hang together.

What do these three lines do:

     a = 0;
     a++;
     a = new supplement();

You seem to do three contradictory things with a there. My guess is that a's meant to be an index to some external thing you don't show.

Then what is

     sup2

supposed to be, some relationship to the supplement() you made earlier?

djna
I made some errors when I pasted in the code and then attempted to generalize for ease of understanding. Goes to show it doesn't pay to code on an empty stomach! =)
chromaloop
A: 
for (var i in json) {

        a = new supplement();

        for (var key in json[i]) {
            var Value = json[i][key];
            a[Key] = Value;
        }
        a.outputProperties();
    }
Zak
A: 

Dave Smith's answer was pretty close to what I needed but it didn't create new objects within the loop. Here's my updated code that provided the desired result:

for (var i in json) {
            theGoods["obj"+i] = new Object();
            for (var key in json[i]) {
                theGoods["obj"+i][key] = json[i][key];
            }
            theGoods["obj"+i].outputProperties();
        }

Each new object is now stored within an array, theGoods[]; I can now reference that object by writing something like: theGoods["obj2"].someMethod();

chromaloop