遍历json并获取每个xth对象值

时间:2019-04-08 07:44:02

标签: javascript json html5 google-sheets-api

如何遍历JSON对象并获取每个nth值并为其生成CSS网格#id元素。

直接示例:我想要数组中第三个元素的每个值,并在div中将它们填充在彼此下面。

valueRanges: Array(1)
0:
majorDimension: "ROWS"
range: "'ma1'!A1:J38"
values: Array(38)
0: (10) ["maandag 1 april 2019", "", "", "", "", "", "", "", "", "week IV"]
1: Array(10)
0: "kafee"
1: "naam"
2: "functie"
3: "van"
4: "tot"
5: "van"
6: "tot"
7: "Subtotaal"
8: "totaal"
9: "Info"
length: 10
__proto__: Array(0)
2: Array(10)
0: ""
1: "Ine"
2: ""
3: "9:30"
4: ""
5: ""
6: "18:00"
7: "8,5"
8: "8"
9: "Reservaties/opmerkingen"
length: 10
__proto__: Array(0)
3: (9) ["", "Michiel", "", "9:30", "", "", "17:30", "8", "7,5"]

我得到的数据

document.getElementById("test").innerHTML = response.result.valueRanges[0].values[0][0];
var request = gapi.client.sheets.spreadsheets.values.batchGet(params);
      request.then(function(response) {
        // TODO: Change code below to process the `response` object:
        console.log(response.result);
        document.getElementById("currentday").innerHTML = response.result.valueRanges[0].values[0][0];
        document.getElementById("StartHourOne").innerHTML = response.result.valueRanges[0].values[2][3];
        document.getElementById("EndHourOne").innerHTML = response.result.valueRanges[0].values[2][6];

        document.getElementById("BarTeamNightNameOne").innerHTML = response.result.valueRanges[0].values[11][1];

我可以为工作表中的每个单元格执行此操作,但是该工作表中有很多单元格。

我希望可以利用JSON中的返回结构。

我已经能够手动添加单元格了。对于每个对象,但是我认为我需要一个for循环。

因此尝试了一个for循环,但这没有用。

valueRanges: Array(1)
0:
majorDimension: "ROWS"
range: "'ma1'!A1:J38"
values: Array(38)
0: (10) ["maandag 1 april 2019", "", "", "", "", "", "", "", "", "week IV"]
1: Array(10)
0: "kafee"
1: "naam"
2: "functie"
3: "van"
4: "tot"
5: "van"
6: "tot"
7: "Subtotaal"
8: "totaal"
9: "Info"
length: 10
__proto__: Array(0)
2: (10) ["", "Ine", "", "9:30", "", "", "18:00", "8,5", "8", "Reservaties/opmerkingen"]

values数组显示0到38个其他数组,这些数组从0到10。现在,例如,每个0到10数组在其父数组上具有相同的数据(0到38)。我该如何迭代以每个第一个值(例如0-14个父数组)填充新的div元素。

我已尝试根据@Kiryhas行为追踪。

但这给了我以下几点。

以下代码:

const object1 = { response.result.valueRanges[0].values[2][1] , 1: response.result.valueRanges[0].values[2][3], 2: response.result.valueRanges[0].values[2][6], 3: response.result.valueRanges[0].values[2][7]};
        console.log(Object.entries(object1));

给我这个结果:

(4) [Array(2), Array(2), Array(2), Array(2)]
0: Array(2)
0: "0"
1: "Ine"
length: 2
__proto__: Array(0)
1: (2) ["1", "9:30"]
2: Array(2)
0: "2"
1: "18:00"
length: 2
__proto__: Array(0)
3: (2) ["3", "8,5"]
length: 4
__proto__: Array(0)

我只想要每个数组以下数组的数组元素1、3、6、7

2: Array(10) (or any other array)
0: ""
1: "Ine"
2: ""
3: "9:30"
4: ""
5: ""
6: "18:00"
7: "8,5"
8: "8"
9: "Reservaties/opmerkingen"

1 个答案:

答案 0 :(得分:1)

根据您对对象中键的关心程度,可以使用htmlObject.keys(yourObject)遍历值或键值对

Object.entries(yourObject):
  

预期输出:数组[“ 1”,数组[“ 1”,“ b”]]

作为参考,请尝试下面的链接

Global_Objects/Object/values

Global_Objects/Object/entries

这将使您可以针对每个Nth值循环进行遍历。