Jarema
Jarema

Reputation: 3586

example of javascript's eval not being evil?

I read some stackOverflow questions and answers more then ten times per day, and... it looks its first time i feel its okey to post something, as i didnt find accurate enought answer.

Im writing some code in nodeJS. Its web interface for big softswitch based on custom asterisk, where in one place i need to get data from post message from website.

The problem is, that that post message containts numerous info named in fashion:

peer1

peer2

peer3

peer4 etc

Instead of dealing with every single one, i did a loop:

 var array = [];
 var i = 0;
        while (typeof eval("req.body.peer" + i) !== 'undefined' &&  eval("req.body.peer" + i) !== '') {
        console.log('petla wisielca');
        //console.log(eval("req.body.peer" + i));
        array.push(eval('req.body.peer' + i));
        i++;
        }

Number filled inputs (actually its html select) is variable.

After creating that array, I deal with rest of things (write peers to file etc) in traditional, non-eval loops.

Am i missing something here, or it's proper way of dealing with such situation?

Thanks in advance!

EDIT:

Looks like i had some kind brain malfunction :).

Solution is very easy,

as kyle cleared it out, to access object variables and for example iterate, all is needed is to use [].

Solution:

var array = []
var i = 0
while (req.body['peer' + i]) {
  array.push(req.body['peer' + i])
  i++
}

Thanks once more Kyle.

Upvotes: 0

Views: 290

Answers (2)

Fiambre
Fiambre

Reputation: 1979

Use of eval is ever evitable, i wrote a plugin that make some dynamic calls of functions, you can check how you can access the object without using eval:

https://github.com/HaSuKrOnOs/jquery-dynFn

Upvotes: 1

Kyle Robinson Young
Kyle Robinson Young

Reputation: 13762

JavaScript objects can be accessed like they're associative arrays:

var array = []
var i = 0
while (req.body['peer' + i]) {
  array.push(req.body['peer' + i])
  i++
}

Upvotes: 1

Related Questions