简体   繁体   中英

Getting the data from json object in javascript

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.

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 + ',';
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM