Pregunta

Tengo este código:

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++
}}

Tomará una matriz JSON que se parece a la siguiente

{"1":{"project":"RobinsonMurphy","task":"Changing blog templates","time":"18\/07\/11 04:32PM"},"2":{"project":"Charli...

El código debe recorrer las filas (que hace) y luego recorrer las columnas de los datos.

El problema que estoy enfrentando es para colocar los datos de la columna en la columna correcta, necesito calcular cuántos datos se están devolviendo en una fila. Probé JSONArray [i]. Length, sin embargo, esto regresa indefinido.

Cualquier ayuda sería apreciada

¿Fue útil?

Solución

No tiene ninguna matrices, solo objetos.

Para contar elementos en un objeto, cree una función simple:

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

Ahora puedes llamar countInObject(jsonArray[i]).

Otros consejos

Como esto:

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

Longitud de un objeto JavaScript

Echa un vistazo a ese violín:http://jsfiddle.net/christophe/qfhc8/

La clave es

for (var j in jsonArray[i]) {

en vez de

while (col <= jsonArray[i].length) {

JSONArray [i]. La longitud no funcionará porque JSONArray [i] es un diccionario, no una matriz. Deberías probar algo como:

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

He estado enfrentando el mismo problema y escribí una función que obtiene todos los valores escalares en una matriz/objeto multidimensional combinado. Si el objeto o la matriz están vacíos, entonces supongo que no es un valor, por lo que no los sumo.

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

O si desea usar esto en producción, incluso podría pensar en agregarlo al prototipo de objeto, como este:

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top