【问题标题】:How to collapse an array of key filtered objects?如何折叠一组关键过滤对象?
【发布时间】:2021-03-01 14:37:47
【问题描述】:

假设我正在从节点存储库中获取一组对象,例如:

const array = [
  {
    id: 1,
    title: "SNKEP1",
    ep: 1,
    season: 1
  },
  {
    id: 2,
    title: "SNKEP2",
    ep: 2,
    season: 1
  },
  {
    id: 3,
    title: "SNKEP3",
    ep: 3,
    season: 1
  },
  {
    id: 4,
    title: "SNKEP1",
    ep: 1,
    season: 2
  },
  {
    id: 5,
    title: "SNKEP2",
    ep: 2,
    season: 2
  },
  {
    id: 6,
    title: "SNKEP3",
    ep: 3,
    season: 2
  },
  {
    id: 7,
    title: "SNKEP1",
    ep: 1,
    season: 3
  },
  {
    id: 8,
    title: "SNKEP2",
    ep: 2,
    season: 3
  },
  {
    id: 9,
    title: "SNKEP3",
    ep: 3,
    season: 3
  }
];

我想得到这样的结果:

const filteredEps = [
  {
    season: 1,
    ep: [{/* filtered eps */}]
  },
  {
    season: 2,
    ep: [{/* filtered eps */}]
  },
  {
    season: 3,
    ep: [{/* filtered eps */}]
  },
];

我如何得到这个结果?

【问题讨论】:

  • 提问前请自己尝试
  • 请先尝试一下(例如使用.filter,或.map,或for 循环),如果您遇到困难,我们可以为您提供帮助。

标签: javascript arrays typescript object


【解决方案1】:

你可以这样做:

let filteredEps = [];
for (const value of array) {
    let [eps] = filteredEps.filter((_eps) => _eps.season === value.season);
    if (eps) {
        eps.ep.push(value.ep);
    } else {
        filteredEps.push({season: value.season, ep: [value.ep]});
    }
}

【讨论】:

    猜你喜欢
    • 2020-10-30
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多