0

I'm working on a database, and it has different columns. How can I get value automatically without typing every column's name and not using eval()?

Working method:

    resultEl.append(
       arg[i].name.toString() +
       arg[i].size.toString() +
       arg[i].price.toString() +
       "<br/>")

I want this without eval:

const dataArray = ['name', 'size', 'price']
let resultEl = $("#result")
resultEl.text("")
for (var i = 0; i < arg.length; i++){
  for (var j = 0; j < dataArray.length; j++){
    const dataraw = arg[i] + "." + dataArray[j] + ".toString()";
    resultEl.append(eval(dataraw))
  }
}

arg is a query from knex('table-name').select

Update

I was evaluating code with <br> tag included and that was the reason it didn't work! However, I still appreciate a non-eval approach.

Community
  • 1
  • 1
Shahriar
  • 1,855
  • 2
  • 21
  • 45
  • Just search for the `knex` docs for the correct syntax to have it return JSON parsable text that includes the headers. But if you want to do it this way, why use eval() ? `arg[i][dataArray[j]].toString()` will also give you that result. Look up `javascript bracket notation dot notation` for more info. – Shilly Jun 18 '19 at 15:06
  • I used the first answer in "How do I loop..." but it only returns 0 and 1s. – Shahriar Jun 18 '19 at 15:12
  • Look at the documentation of these loops. You get 0 and 1 because it's an array instead of an object. Arrays need a different kind of loop than objects. For arrays, your own for-loop will suffice. For objects, use the `for .. in` or `for ... of` as described in the duplicate. Also do yourself a favor and look up all the array methods, like `Array.forEach()`. These are builtin methods to loop over arrays that I personally find way easier to work with than basic `for` loops. – Shilly Jun 18 '19 at 15:16

0 Answers0