Valor_ Valor_ - 4 months ago 6
JSON Question

Create object from splitted strings

I need some help from you guys. I need to create a object from splitted string. Let me show you my code with explanation and hope you guys can help me.
So this is my current code

for(d in data){
var item = d.split('_');
console.log(item + " " + data[d]);
if(item[0] == 'partnerX'){
//Rest of the code goes here
}else if(item[0] == 'partnerY'){
//Rest of the code goes here
}
}


My
console.log(d + " " + data[d])
inside for loop is

partnerX_row1_id 10101010
partnerX_row10_id 79899899


My
console.log(d.split('_') + data[d])
is

partnerX,row1,id 10101010
partnerX,row10,id 79899899
partnerX,row11,id 99999999
partnerX,row1,name test13
partnerX,row10,name test10
partnerX,row11,name test1
partnerY,row1,id 10101010
partnerY,row10,id 79899899
partnerY,row11,id 99999999
partnerY,row1,name test12
partnerY,row10,name test77
partnerY,row11,name test889


My problem is that end result should look like this but i just can't figure out how to properly loop through data, then push it to array and convert array to object or just directly create object, which would look like this one.

{
"partnerx": {
"partnerx_row1" : {
"id": 3456788,
"name": "creditor 1"
},
"partnerx_row10" : {
"id": 79899899,
"name": "test10"
},
"partnerx_row11" : {
"id": 99999999,
"name": "test1"
}
},
"partnery": {
"partnery_row1" : {
"id": 10101010,
"name": "test12"
},
"partnery_row10" : {
"id": 79899899,
"name": "test77"
},
"partnery_row11" : {
"id": 99999999,
"name": "test889"
}
}
}


I hope you guys can help me. If you need any additional informations, please let me know and i will provide. Thank you in advance

Answer

Here goes the code. The result is stored in obj.

obj = {};
for(d in data) {
   var item = d.split('_');
   item[0] = item[0].toLowerCase();
   if (obj[item[0]] == undefined) {
       obj[item[0]] = {};
   }
   if (obj[item[0]][item[0] + "_" + item[1]] == undefined) {
       obj[item[0]][item[0] + "_" + item[1]] = {};
   }
   obj[item[0]][item[0] + "_" + item[1]][item[2]] = data[d];
}
Comments