0

I am making some common function where in I pass the array, name of field from array, value of field in array and return field name to return value as below

function arrayFilter(_array, findField, value, returnField) {
 var temp = "_array[i]." + findField;
 var retValue = "";
 for (var i = 0; i < _array.length; i++) {
   if (eval(temp) == value) {
  return eval("_array[i]." + returnField);
  }
 }
}

But when I read on Internet I found that eval is not good, it can have string injection attack.

So somebody help on above.

Milind
  • 1,855
  • 5
  • 30
  • 71
  • Have you got an example of the type of array you're looping over? – Andy Feb 24 '14 at 11:42
  • I ask only because there have got to be far better ways of doing what you want to do if you restructure your array better. – Andy Feb 24 '14 at 11:44
  • I don't really understand why even people ask that. How do they learn about `eval` before extremely basics that is `[]`? – Oleg V. Volkov Feb 24 '14 at 11:46

2 Answers2

3

Instead of:

return eval("_array[i]." + returnField);

Try:

return _array[i][returnField];

And also read this article.

Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
1

You can use the square bracket notation for accessing properties when the value of your key is unknown.

function arrayFilter(_array, findField, value, returnField) {
 var temp = _array[i][findField];
 var retValue = "";
 for (var i = 0; i < _array.length; i++) {
   if (temp == value) {
     return _array[i][returnField];
   }
 }
}
techfoobar
  • 65,616
  • 14
  • 114
  • 135