timkado timkado - 1 year ago 146
Javascript Question

JavaScript Parsing: JSON to Javascript object

Hi I am fairly new to JavaScript and I am a little confused with what to do with an object like the one below. How can I convert this to an array pt where each entry has the properties selid x,y,z?

this is what I see in the Chrome console:

Object {pt[2][y]: "1.3571934700012207", pt[0][selid]: "2", pt[0][z]: "0", pt[3][x]: "3.6684491634368896", pt[2][z]: "0"…}

If I am trying to access pt like in the example below :

var X = pt[2].x;

I get and error "Cannot read property of undefined". I assume that this is because the object is more like a dictionary with "pt[2][y]" as key and "1.3571934700012207" as value.
However I want to access it like an array pt with objects that have the property x,y,z, selid.
Is there a way to convert/parse the data into the format I want?
Thanks a lot in advance.

Answer Source

You have say in comment that you do console.log(data) to get obj content. So probably you should do

var X = data["pt[2][x]"];

If you want to convert it into array pt you should do:

var data = {
    "pt[0][x]" : 1, 
    "pt[1][x]" : 2, 
    "pt[2][y]" : 3, 
    "pt[2][z]" : 3

var pattern = /^pt\[([^\]]+)\]\[([^\]]+)\]$/i ;

var pt = [];
for( var key in data ){

    if ( pattern.test(key) ){
        var m = key.match(pattern);
        if( !pt[m[1]] ) pt[m[1]] = {};
        pt[m[1]][m[2]] = data[key];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download