将对象数组转换为对象数组

时间:2020-03-18 13:04:38

标签: javascript arrays object grouping javascript-objects

我正在从足球(足球)API中检索数据。我需要的特定数据是对象数组(306个对象)。每个对象都有一个称为matchday的属性,具有数字值。我想对共享相同属性的所有对象进行分组,并将它们存储在数组中。最后,我需要的是一组对象数组。

对象数组示例:

[
  {id: 264796, matchday: 1, …},
  {id: 264797, matchday: 1, …},
  {id: 264798, matchday: 2, …},
  {id: 264800, matchday: 2, …},
]

我想要的内容如下:

[
  [{id: 264796, matchday: 1, …},{id: 264797, matchday: 1, …}],
  [{id: 264798, matchday: 2, …},{id: 264800, matchday: 2, …}],
]

4 个答案:

答案 0 :(得分:4)

您可以将.reduce()Object.values()结合使用以获取所需的输出:

const data = [
  {id: 264796, matchday: 1}, {id: 264797, matchday: 1},
  {id: 264798, matchday: 2}, {id: 264800, matchday: 2}
];

const result = Object.values(
  data.reduce((r, c) => {
    r[c.matchday] = r[c.matchday] || [];
    r[c.matchday].push(c);
    return r;
  }, {})
);

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

答案 1 :(得分:1)

我们可以使用reduce

const arr = [
  {id: 264796, matchday: 1},
  {id: 264797, matchday: 1},
  {id: 264798, matchday: 2},
  {id: 264800, matchday: 2},
]

const result = arr.reduce((acc, item) => {

  if (!acc.find(accSubArr => accSubArr.find(accSubArrItem => accSubArrItem.matchday === item.matchday))) {
    acc.push(arr.filter(arrItem => arrItem.matchday === item.matchday))
  }
  return acc;
}, [])

console.log(result)

答案 2 :(得分:1)

您可以尝试以下方法:

const data = [{
    id: 264796,
    matchday: 1
  },
  {
    id: 264797,
    matchday: 1
  },
  {
    id: 264798,
    matchday: 2
  },
  {
    id: 264800,
    matchday: 2
  },
]

const group = data
  .map(d => d.matchday)
  .filter((v, i, c) => c.indexOf(v) === i)
  .map(i => data.filter(d => d.matchday === i))

console.log(group)

答案 3 :(得分:1)

要添加到现有答案中,这是使用Mappredicate来确定分组依据值的另一种方法:

const groupBy = predicate => items => 
     Array.from(items.reduce((agg, next) => {
        const key = predicate(next);
        return agg.set(key, [].concat(agg.get(key) || []).concat(next));
    }, new Map()).values());


const data = [
{name: 'A', key: 1},
{name: 'B', key: 1},
{name: 'C', key: 2},
{name: 'D', key: 2},
{name: 'E', key: 3}
];

const grouped = groupBy(x => x.key)(data);

有趣的是,这是groupBy的递归版本:

const groupBy = predicate => function group([next, ...items], grouped = new Map()) {
    if (!next) {
        return Array.from(grouped.values())
    }

    const key = predicate(next);
    return group(items, grouped.set(key, [...(grouped.get(key) || []), next]));
}

这到底是什么,这是一种添加到组合中的更必要的方法:

const groupBy = predicate => items => {
    const cache = {};

    for(item of items) {
        const key = predicate(item);
        cache[key] = [].concat(cache[key]).concat(item).filter(x => x)
    }

    return Object.values(cache);
}