1

I would like to figure out how to concatenate an object in a for loop; eval() works fine, but I would like optimum efficiency and much of what I have searched on Google leads me to believe eval() is not a safe choice. I have looked at other examples that relate to eval(), however, none seem to be the same case.

I'm a beginner with Javascript, so apologies if this has an easy resolution.

objFunction: function () {
        var concat1;
        var concat2;
        $('table tbody tr').each(function (i) {
            i++;
            for (var x = 1; x <= 4; x++) {                   
                concat1 = 'obj1.obj2.obj3.step' + i + '[' + x + ']' + '.name';
                concat2 = 'obj1.obj2.obj3.step' + i + '[' + x + ']' + '.icon';

                console.log(eval(concat1));
                console.log(eval(concat2));
});
}

Thanks,

Bergi
  • 630,263
  • 148
  • 957
  • 1,375

3 Answers3

2

Well, you're already using the bracket notation member operator. Just use it for the stepN as well:

function () {
    $('table tbody tr').each(function (i) {
        i++;
        for (var x = 1; x <= 4; x++) {
            console.log(obj1.obj2.obj3['step'+i][x].name);
            console.log(obj1.obj2.obj3['step'+i][x].icon);
        } // <-- you're missing this brace, btw
    });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Instead of:

concat1 = 'obj1.obj2.obj3.step' + i + '[' + x + ']' + '.name';
concat2 = 'obj1.obj2.obj3.step' + i + '[' + x + ']' + '.icon';
console.log(eval(concat1));
console.log(eval(concat2));

You can use:

console.log(obj1.obj2.obj3['step' + i][x].name);
console.log(obj1.obj2.obj3['step' + i][x].icon);

That would have the same effect. obj1.obj2 is the same as obj1['obj2']. That's just a different notation.

Also your for seems to be missing its closing curly bracket (}).

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
0

Does this not do what you want?

objFunction: function () {
    var concat1;
    var concat2;
    $('table tbody tr').each(function (i) {
        i++;
        for (var x = 1; x <= 4; x++) {                   
            console.log(obj1.obj2.obj3['step' + i][x].name);
            console.log(obj1.obj2.obj3['step' + i][x].icon);
    });
}

I haven't tested this out, but it should be pretty close to what you require. Try experimenting with the syntax a bit and splitting out pieces of the nesting into sub-expressions assigned to other variables to figure out where it's going wrong, if it's not working right off the bat.

crowder
  • 724
  • 5
  • 13