根据数组中的值将单个数组拆分为多个数组。的JavaScript

时间:2017-04-29 17:59:32

标签: javascript arrays

这是关于分组的上一个问题的延续。我有一个下面的结构文件和我想做的,而不是简单地隔离一个我想循环遍历整个数组的id(想象1000+ ids)并为每个创建单独的数组,然后我可以进一步处理。因此,在下面的示例中,id1将在一个数组中组合在一起,而id2将在另一个数组中组合在一起。一旦我将每个ID分成一个单独的数组,我就会继续根据一组条件进一步过滤每个ID。

[{col1: 'id1', col2: '123', col3: '12/01/12'},
{col1: 'id1', col2: '100', col3: '12/01/12'},
{col1: 'id2', col2: '-100', col3: '12/01/12'},
{col1: 'id2', col2: '123', col3: '13/01/12'}]

有关打破阵列以及如何调用单个ID阵列的最佳方法的任何建议将非常感激。

提前致谢

2 个答案:

答案 0 :(得分:3)

您可以使用给定的id作为对象的键,并收集自己数组中的项目。



var data = [{ col1: 'id1', col2: '123', col3: '12/01/12' }, { col1: 'id1', col2: '100', col3: '12/01/12' }, { col1: 'id2', col2: '-100', col3: '12/01/12' }, { col1: 'id2', col2: '123', col3: '13/01/12' }],
    object = data.reduce(function (r, o) {
        r[o.col1] = r[o.col1] || [];
        r[o.col1].push(o);
        return r;
    }, Object.create(null));
    
console.log(object);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:1)

如果您想将具有相同ID的数组组合在一起,请尝试以下代码。



var a  = [{col1: 'id1', col2: '123', col3: '12/01/12'},
{col1: 'id1', col2: '100', col3: '12/01/12'},
{col1: 'id2', col2: '-100', col3: '12/01/12'},
{col1: 'id2', col2: '123', col3: '13/01/12'}];
var currentID = a[0].col1;
var group = [];
var collectionOfIDs = [];
a.forEach(function(v, i) {
  //console.log(i,v);
  if (currentID == v.col1) {
    collectionOfIDs.push(v);
  } else {
    group.push(collectionOfIDs);
    currentID = v.col1;
    collectionOfIDs = [v];
  }
});
group.push(collectionOfIDs);
console.log(group)