0

I have this object from a PHP API:

[Object { span=1,  caption="Particular",  master=true},
Object { span=5,  caption="Loan Class 1"},
Object { span=5,  caption="Loan Class 2"},
Object { span=5,  caption="Loan Class 3"}]

The desired output would be:

## Particular   Loan Class 1    Loan Class 2  Loan Class 3 ##

I tried to do this :

var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
for (var index in arrData[0]) {
row += index + ',';}
row = row.slice(0, -1);
CSV += row + '\r\n';

What the csv looks like

## span   caption   master ##  

Please help how to get the caption value and if there's a script that will output this in excel since there is a need to add some merging of columns.

Barmar
  • 741,623
  • 53
  • 500
  • 612
bluerain25
  • 13
  • 4

2 Answers2

1

You should be iterating over the whole array, not just the object in arrData[0]. And you should not use for (index in object), that just sets index to the keys, not the values. Then to access the captions, you use .caption.

for (var i = 0; i < arrData.length; i++) {
    row += arrData[i].caption + ',';
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • whew its just that i'm quite new to this json and javascript thing. been doing php but with frameworks where there is no need to do front end coding. thank you @barmar just what I needed. – bluerain25 Apr 07 '16 at 09:36
0

For the caption part you could use this:

var row = arrData.map(function(element) {
  return element.caption;
}).join(' ');

.map is used to extract the caption value of all elements in the array. The resulting array values are concatenated with .join. You can specify the separator as a parameter for the .join function.

Writing anything in Excel file format is not trivial. Unless you want the result in CSV format (which your code example implies). For that you might want to take a look at this answer.

Community
  • 1
  • 1
eschmidt
  • 91
  • 3
  • yes as per discussion with the clients they are fine with csv but if we can do it in excel where we can follow formats from the sample we had much better. as you can see there's that "span" in the object. span is the number of columns for that certain caption – bluerain25 Apr 07 '16 at 09:42