0

I am trying to create JSON object entered into textbox using below code.

colnames is array of columns from table colnames = [DEPTNO,DNAME],

I am trying to create JSON object dynamically. e.g.

tableInsert.DEPTNO = 100; tableInsert.DNAME= sales;

but when i run it, it always complain console.log (eval ("tableInsert." + col)); is undefined. Any help..

  document.getElementById("insercols").onclick = function(){
    var tableInsert ='';
    var colvalue='';
    console.log("cols are " + colnames);
    for (col of colnames){
        colvalue = document.getElementById(col).value;
        eval ("tableInsert." + col + " = " + "typeof "+  colvalue);

        console.log("tableInsert." + col + " = " + "typeof "+  colvalue);
        console.log (eval ("tableInsert."  + col));

    }
}
kuldipem
  • 1,719
  • 1
  • 19
  • 32
  • 2
    eval is evil .... and you don't need to **eval** for this – Jaromanda X Sep 18 '15 at 09:20
  • 5
    1) it's JSON, not jason. 2) There is only one JSON object in JavaScript, and it has methods `parse` and `stringify` on it. You are creating (or rather, should be creating) a plain JS object. 3) You are using `eval`. `eval` is evil. Use `tableInsert[col]` instead. 4) `tableInsert` is a string. Normally you'd set attributes on a plain object `{}`, not on a string `''`. – Amadan Sep 18 '15 at 09:21
  • @JaromandaX: `eval` does not return `undefined`, it returns whatever the `eval`'d snippet evaluates to. (Well, okay, `eval("void 7")` does return `undefined`.) It is still evil. – Amadan Sep 18 '15 at 09:26
  • `tableInsert[col]` is easy, but how to do `typeof dynamicVariableName` without `eval`? Maybe there is a better way to design this. Probably with a lookup table. What values can `colvalue` have? – Thilo Sep 18 '15 at 09:29
  • Maybe `typeof window[colvalue]`? Still seems like a terrible idea. – Thilo Sep 18 '15 at 09:30
  • i am returning **colvalue** from input text box, colvalue = document.getElementById(col).value; – user5310556 Sep 18 '15 at 09:31
  • And what do you type in that box? What is that `typeof` supposed to do anyway? – Thilo Sep 18 '15 at 09:32
  • as colnames = [DEPTNO,DNAME], so values will be string and number – user5310556 Sep 18 '15 at 09:34
  • @Jaromanda X i tried tableInsert[col] = typeof colvalue; its still undefined.. – user5310556 Sep 18 '15 at 09:35
  • what do you expect from `eval ("tableInsert." + col + " = " + "typeof "+ colvalue);` ? – maioman Sep 18 '15 at 09:35
  • this is what i am expecting tableInsert.DEPTNO = 100; tableInsert.DNAME= sales, but it never set value.. – user5310556 Sep 18 '15 at 09:36
  • @user5310556 - if typeof colvalue returns "undefined" then colvalue is undefined - simple – Jaromanda X Sep 18 '15 at 10:57

1 Answers1

0

define tableinsert as and try again..

var tableInsert = {};
tableInsert[col] = typeof colvalue;
Nomad
  • 1,019
  • 4
  • 16
  • 30