使用oud jQuery在JavaScript中迭代嵌套对象

Iterating nested object in JavaScript withoud jQuery

本文关键字:迭代 嵌套 对象 JavaScript oud jQuery 使用      更新时间:2023-09-26

我正在尝试遍历一个嵌套对象。

    array=[
  {
    id: 2,
    items: [
      {
        id: 12
      },
      {
        id: 13
      },
      {
        id: 14
      }
    ]
  },
  {
    id: 3,
    items: [
      {
        id: 15
      },
      {
        id: 16
      },
      {
        id: 17
      },
      {
        id: 18
      },
      {
        id: 19
      }
    ]
  },
  {
    id: 4,
    items: [
      {
        id: 20
      },
      {
        id: 21
      }
    ]
  },
  {
    id: 5,
    items: [
      {
        id: 22
      }
    ]
  }
];

我需要将所有的ID推送到一个数组中,以便我们可以在上面的代码中看到。类似这样的东西:

arrayOfId = [2, 12, 13, 14, 3, 15, 16, 17, 18, 19, 4, 20, 21, 5, 22];

我试着自己做,在这里找到了一些例子,但它们是基于jQuery的。我在我的项目中使用Angular。

也许有人知道用普通JS或Angular来解决这个问题?

非常感谢。

它实际上非常简单

  1. 获取数组的长度
  2. 循环通过该阵列并推送具有当前id值的新阵列(ids(
  3. 获取嵌套数组的长度
  4. 循环遍历,并将嵌套的id也推送到该数组中

var l=array.length,i=0,ids=[];
for(;i<l;i++){
 ids.push(array[i].id);
 var nested=array[i].items,nl=nested.length,j=0;
 for(;j<nl;ids.push(nested[j++].id));
};
console.log(ids);
alert(ids);
//ids=[2,12,13,14,3,15,16,17,18,19,4,20,21,5,22];

在这个例子中,我展示了编写for循环的各种方法。此外,通过缓存length和其他变量(如nested阵列(,性能得到了提高。我还想提到,对于像这样的简单函数,您必须通过多维数组/对象LOOP,不鼓励使用forEachmapfilter或其他"新"的本地javascript函数,因为与标准while&for循环(1(。它们大约慢3-4倍。另一方面,如果您知道您的多维数组没有那么大,并且客户端使用现代浏览器,那么map解决方案就是"短代码"的替代方案(2(。

演示

http://jsfiddle.net/axaog3n2/1/

1https://jsperf.com/for-vs-foreach/2

2https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

如果你有任何问题,直接问。

您可以在另一个for循环中使用for循环。

for (var i = 0; i < array.length; i++) {
  arrayOfId.push(array[i].id);
  for (var j = 0; j < array[i].length; j++) {
    arrayOfId.push(array[i][j]);
  }
}

使用Array.map

//This will give a 2d array of ids [[2,3],[2,3]];
var ids = array.map(function(item) {
    return item.items.map(function(obj) {
        return obj.id
    })
});
//Now flatten and merge
var idList = [];
idList = idList.concat.apply(idList , ids);
//Output:
//[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]

演示:http://jsfiddle.net/2kmozrr7/

简单用于循环

var arrayOfId = [];
for (var i = 0; i < array.length; i++) {
    arrayOfId.push(array[i].id);
    if (array[i]['items'] != undefined && array[i].items.length > 0) {
        for(var j = 0; j < array[i].items.length; j++) {
            arrayOfId.push(array[i].items[j].id);
        }
    }
}
var ids = [];
for (var x = 0; x < array.length; x++) {
    ids.push(array[x].id);
    if (array[x].items) {
        var items = array[x].items;
        for (var y = 0; y < items.length; y++) {
            if (items[y].id) {
                ids.push(items[y].id);
            }
        }
    }
}

任何比这更嵌套的方法,都需要使用递归函数来理智地完成。

var results = [];
function build(array, results) {
    for (var x = 0; x < array.length; x++) {
        results.push(results[x].id);
        if (results[x].items) {
            build(results[x].items, results);
        }
    }
}
build(thatObject, results);
// create array for result
var b = [];
// iterate over the source array
array.forEach(function (outer) {
    // get the id property and push the value to the result array
    b.push(outer.id);
    // iterate over the items
    outer.items.forEach(function (inner) {
        // get the id property of the inner array object and push the value to the result array
        b.push(inner.id);
    });
});