使用循环返回嵌套的json值(谷歌电子表格)

时间:2016-04-13 09:14:25

标签: javascript arrays json google-sheets javascript-objects

我有这个google电子表格脚本,可以输入json格式的图书数据。我没有问题显示书名和作者,但他" offerData"对象可以包含不同数量的元素(来自卖家的价格),具体取决于书籍。现在我创建了一个循环并存储了如下所示的offerData值:

 SELECT
 CI_ID,
 Status,
 "status-Reason",
 CI_name,
 Serial_num,
 Manufacturer,
 model,
 receipT_date,
 refresh,
 core_id,
 departm
FROM
 `laptop` laptop
WHERE
 Core_id = $P{core}
 or refresh >= $P{datef}
 and refresh <= $P{datet}
 and departm <> $P{DepartM}

并返回这样的数据:

   price[i] = offerdata.offers[i]["price"];
   condition[i] = offerdata.offers[i]["condition"];
   seller[i] = offerdata.offers[i]["seller"]["displayName"];

显然,这仅返回3个卖家的价格,条件,卖家信息。问题在于,一本书并不总是有3个卖家,它可以是1到10个左右。

我的问题是如何在此处退回所有offerData(价格/条件/卖家)? :

 var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];

-

 var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];

2 个答案:

答案 0 :(得分:0)

答案

var resultRow = [];
resultRow[0] = [];
resultRow[0][0]=title;
resultRow[0][1]=specstag;
for (var i = 0; i < arrayLength; i=1+3) {
  resultRow[0][3*i+2]=price[i];
  resultRow[0][3*i+3]=condition[i];
  resultRow[0][3*i+4]=seller[i];
}

你应该如何思考它是看到数组中元素的索引,然后找到i和你想要的索引之间的关系

var resultRow = [
  [
    title, //[0][0]
    specstag, //[0][1]
    price[0], //[0][2]
    condition[0], //[0][3]
    seller[0], //[0][4]
    price[1], //[0][5]
    condition[1], //[0][6]
    seller[1], //[0][7]
    price[2], //[0][8]
    condition[2], //[0][9]
    seller[2]//[0][10]
  ]
];

答案 1 :(得分:0)

您可能正在寻找类似的东西;

var data = {     title: null,
               spcstag: null,
                   pcs: [],
           };

offerData.offers.forEach( p => { var pcsData = {};
                                 !!data.title || data.title = p.title;
                                 !!data.specstag || data.specstag = p.specstag;
                                 pcsData.price = p.price;
                                 pcsData.condition = p.condition;
                                 pcsData.seller = p.seller;
                                 data.pcs.push(pcsData);
                               });