ni8mr ni8mr - 4 months ago 9
Javascript Question

Creating a comma separated string from an Object

I have an array of Object from which i am trying to generate a comma separated string. Here is my code -

arrData = {
"bl_number": "TCLPKGCTG1603200",
"comodity": "GEN",
"container": {
"container_id": "CRSU9007907",
"full_empty": true,
"type": 1
},
"flc_lcl": "FCL",
"weight": "25.0000"
}

var row = "";

for (var index in arrData) {
if(index == 'container'){
for(var index_of_container_json in arrData[index]){
if(index_of_container_json == 'container_id'){
row = 'CONTAINER' + ',';
}else if(index_of_container_json == 'full_empty'){
row = 'F/E' + ',';
}
}
}else if(index == 'bl_number'){
row += 'B/L No' + ',';
}else if(index == 'flc_lcl'){
row += 'FCL/LCL' + ',';
}else if(index == 'comodity'){
row += 'COMMODITY' + ',';
}else if(index == 'weight'){
row += 'WGT' + ',';
}
}


I am saving comma separated string in row variable. The final result is

F/E,B/L No,FCL/LCL,COMMODITY,WGT


My problem is, somehow CONTAINER is always going missing from row. I need my final result like this

CONTAINER,F/E,B/L No,FCL/LCL,COMMODITY,WGT

Answer
  1. I see error here: arrData = [.. ] it should be arrData = { ... }
  2. Exchange row = ... to row += ... everywhere