计算多维数组中的元素数量

4

Ive got this code:

loadData : function(jsonArray) {
var id = $(this).attr("id");

for(var i in jsonArray) {
    $("#"+id+" tbody").append('<tr class="entry-details page-1 entry-visible" id="entry-'+i+'"></tr>');

    var header = {
        1: "time",
        2: "project",
        3: "task"
    }
    var col = 1;
    while(col <= jsonArray[i].length) {
        $("#"+id+" tbody #entry-"+i).append("<td>"+jsonArray[i][header[col]]+"</td>")
        col++
}}

它将接受类似以下的JSON数组:
{"1":{"project":"RobinsonMurphy","task":"Changing blog templates","time":"18\/07\/11 04:32PM"},"2":{"project":"Charli...

代码应该循环遍历行(它已经做到了),然后循环遍历数据的列。
我面临的问题是,为了将列数据放在正确的列中,我需要计算一行返回多少个数据。我尝试过 jsonArray[i].length,但这会返回未定义。
任何帮助都将不胜感激。
5个回答

4

你没有任何数组,只有对象。

要计算对象中的项目,请创建一个简单的函数:

function countInObject(obj) {
    var count = 0;
    // iterate over properties, increment if a non-prototype property
    for(var key in obj) if(obj.hasOwnProperty(key)) count++;
    return count;
}

现在,你可以调用countInObject(jsonArray[i])函数。

抱歉,我的错,我是Stack Overflow的新手!已经修复 :) - Brad Morris

2

就像这样:

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// Get the size of an object
var size = Object.size(myArray);

JavaScript对象的长度


0

0

jsonArray[i].length不起作用,因为jsonArray[i]是一个字典而不是数组。你应该尝试类似这样的代码:

for(var key in jsonArray[i]) {
     jsonArray[i][key]
}

0

我一直面临着同样的问题,于是我编写了一个函数,可以获取多维数组/对象中的所有标量值并将它们相加。如果对象或数组为空,则我认为它不是一个值,因此不会对其进行求和。

function countElements(obj) {
  function sumSubelements(subObj, counter = 0) {
    if (typeof subObj !== 'object') return 1; // in case we just sent a value
    const ernation = Object.values(subObj);
    for (const ipated of ernation) {
      if (typeof ipated !== 'object') {
        counter++;
        continue;
      }
      counter += sumSubelements(ipated);
    }
    return counter;
  }
  return sumSubelements(obj);
}

let meBe = { a: [1, 2, 3, [[[{}]]]], b: [4, 5, { c: 6, d: 7, e: [8, 9] }, 10, 11], f: [12, 13], g: [] };
const itution = countElements(meBe);
console.log(itution); // 13

let tuce = [1,2];
console.log(countElements(tuce)); // 2

console.log(countElements(42)); // 1

或者如果你想在生产环境中使用它,甚至可以考虑将其添加到对象原型中,像这样:

Object.defineProperty(Object.prototype, 'countElements', {
  value: function () {
    function sumSubelements(subObj, counter = 0) {
      const subArray = Object.values(subObj);
      for (const val of subArray) {
        if (typeof val !== 'object') {
          counter++;
          continue;
        }
        counter += sumSubelements(val);
      }
      return counter;
    }
    return sumSubelements(this);
  },
  writable: true,
});

console.log(meBe.countElements()); // 13
console.log([meBe].countElements()); // 13; it also works with Arrays, as they are objects

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接