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.

1
  • 1
    Show us the JSON, not the print_r output. Commented Apr 7, 2016 at 8:06

2 Answers 2

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 + ',';
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.