如何计算JSON对象中的值?

时间:2018-08-22 18:07:47

标签: javascript jquery html json

我具有以下JSON结构。我正在尝试使用此对象来计算维数(在本例中为4)。每行的级别数?

我该如何实现?

 {
  "row": {
    "0": {
      "dimension": "Marketing",
      "level1": "testlevel1",
      "level2": "testlevel2",
      "level3": "testlevel3"
    },
    "1": {
      "dimension": "Sales",
      "level1": "Northeast",
      "level2": "NorthWest",
      "level3": "WestCoast"
    },
    "2": {
      "dimension": "Distribution",
      "level1": "Northeast",
      "level2": "NorthWest",
      "level3": "WestCoast"
    },
    "3": {
      "dimension": "Campaign",
      "level1": "Northeast",
      "level2": "NorthWest",
      "level3": "WestCoast"
    }
  }
}

当我尝试

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    console.log(obj[key]);
  }
}

它只打印一行。

3 个答案:

答案 0 :(得分:0)

let obj = /..Json../
for(let elem of obj.row) {
  let count = 0;
  for(let key in elem) {
    if(key.indexOf('level') != -1) {
      count++
    }
  }
  console.log(count)
}

只要您有嵌套的对象,就应该先进入“行”,然后循环遍历其键并计算级别。

答案 1 :(得分:0)

如果您只想对它们进行计数,就可以这样做。

 var count = 0;
for (var key in obj.row) {
  if (key.dimension) {
   count++;
  }
}
console.log(count);

答案 2 :(得分:0)

尝试一下:

-XX:+UseG1GC