开发者

Create new object within a for-in-loop

开发者 https://www.devze.com 2023-01-16 16:20 出处:网络
I want to create a new object and assign some properties for each array stored within some json. I have this mostly working except...

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 i开发者_Python百科s 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.


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();
}


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?


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();


for (var i in json) {

        a = new supplement();

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

精彩评论

暂无评论...
验证码 换一张
取 消