从 json object 获取数据 javascript

Getting the data from json object in javascript

我有这个 object 来自 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"}]

所需的输出为:

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

我试过这样做:

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';

csv 是什么样的

## span   caption   master ##  

请帮助如何获取标题值,以及是否有一个脚本可以在 excel 中输出该值,因为需要添加一些列合并。

您应该遍历整个数组,而不仅仅是 arrData[0] 中的对象。你不应该使用 for (index in object),它只是将 index 设置为键,而不是值。然后要访问字幕,请使用 .caption.

for (var i = 0; i < arrData.length; i++) {
    row += arrData[i].caption + ',';
}

对于标题部分,您可以使用:

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

.map用于提取数组中所有元素的标题值。生成的数组值与 .join 连接。您可以将分隔符指定为 .join 函数的参数。

以 Excel 文件格式编写任何内容都不是小事。除非您想要 CSV 格式的结果(您的代码示例暗示)。为此,您可能想看看这个 answer.