Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string to an object

I'm new to programming and I wanted to develop my skills by working on a small project.

I am creating a Sudoku app, using HTML/JavaScript. I have a large number (81) of 'div' elements in HTML, and I want to assign content to them using by changing their innerHTML. Using the two for loops, I go through all 81 variables and re-create their name in 'x', which I then pass to assign_cell() to assemble the code.

puzzle_inc holds the puzzle itself (9..47.8.2..821.. etc; "." denotes empty cell), and I use a counter function to go through its characters one by one, assigning them to each 'div'.

After much testing and searching, I found out that my problem is that x is of 'string' type and the code in assign_cell() will not work. In this case, x will always be equal to something like "c01".

What I've been trying to do is to convert x to an object type. I have tried using JSON.parse() to fix the issue but probably due to my lack of knowledge in the field I have been unsuccessful.

I'm not sure how else to approach this but any help would be really appreciated.

Thank you.

function assign_cell(flag, arr1, arr2) {
    if(flag === 1) {
        arr1.innerHTML = puzzle_inc[arr2];
    } else if(flag === 2) {
        arr1.innerHTML = null;
    } else {
        alert("Error in function assign_cell()");
    }   
}

for(var i = 0; i < 9; i++){
    for(var k = 0; k < 9; k++){
        var a = counter();
        var x = "c"+i+k;
        if(puzzle_inc[a] != '.') {
            assign_cell(1, x, a);
        } else {
            assign_cell(2, x, a);
        }
    }
}

EDIT: I've been asked for the whole code, to better help answer my question. Please find it below. Thank you for the answers!

PHP JS

like image 707
Raduchi Avatar asked Nov 06 '22 21:11

Raduchi


1 Answers

have you tried eval()

var stringval='[1,2,3]';
var value=eval(stringval);
console.log(value);//=>[1, 2, 3]
like image 139
kunal verma Avatar answered Nov 10 '22 01:11

kunal verma