Search code examples
javascriptarrays

Can i convert array in string to array?


I am having array like below

'[{"stuff_width":200,"_id":"cPEzHYNLHhyHbtK9MJ7F","stuff_weight":400,"stuff_length":100,"image":["cPEzHYNLHhyHbtK9MJ7F_0","cPEzHYNLHhyHbtK9MJ7F_1"],"quantity":5,"stuff_type":"Cunstruction Material \\/ Cement","stuff_height":300},{"stuff_width":200,"_id":"F5OhdfGnoHpffkpR82KK","stuff_weight":300,"stuff_length":400,"image":["F5OhdfGnoHpffkpR82KK_0"],"quantity":5,"stuff_type":"Furniture \\/ Wood Items","stuff_height":400}]'

Can I just remove the first and last single quotes and use it as simple array ?

I have use something like

courier_items.slice(1, -1);

But it gives me result like below

{"stuff_width":2,"_id":"ubcpQhAmIiGPyrqm7OpT","stuff_weight":12,"stuff_length":1,"image":["ubcpQhAmIiGPyrqm7OpT_0","ubcpQhAmIiGPyrqm7OpT_1"],"quantity":1,"stuff_type":"Cunstruction Material \/ Cement","stuff_height":12}

It still behave like string.

I want array not only object


Solution

  • Use JSON.parse and not slice(), as JSON.parse will parse the JSON array and give you output as an array:

    var str = '[{"stuff_width":200,"_id":"cPEzHYNLHhyHbtK9MJ7F","stuff_weight":400,"stuff_length":100,"image":["cPEzHYNLHhyHbtK9MJ7F_0","cPEzHYNLHhyHbtK9MJ7F_1"],"quantity":5,"stuff_type":"Cunstruction Material \\/ Cement","stuff_height":300},{"stuff_width":200,"_id":"F5OhdfGnoHpffkpR82KK","stuff_weight":300,"stuff_length":400,"image":["F5OhdfGnoHpffkpR82KK_0"],"quantity":5,"stuff_type":"Furniture \\/ Wood Items","stuff_height":400}]';
    
    var res = JSON.parse(str);
    
    console.log(res);

    Parse the data with JSON.parse(), and the data becomes a JavaScript object.