【问题标题】:How to order an array of objects in array of categories in javascript?如何在javascript中对类别数组中的对象数组进行排序?
【发布时间】:2020-07-21 20:25:57
【问题描述】:

我有以下对象数组

{
  "nome": "jose",
  "categoria": [
    { "id": "1" },
    { "id": "3" },
  ]
},
{
 "nome": "maria",
  "categoria": [
    { "id": "2" },
  ]
},
{
  "nome": "pedro",
  "categoria": [
    { "id": "1" },
  ]
}

我必须在另一个类别数组中重新排序。像这样的:

{
  "id": "1",
  "pessoas": [
    {
      "nome": "jose",
      "categoria": [
        { "id": "1" },
        { "id": "3" },
      ]
    },
    {
      "nome": "pedro",
      "categoria": [
        { "id": "1" },
      ]
    },
  ]
},
{
  "id": "2",
  "pessoas": [
    {
      "nome": "maria",
      "categoria": [
        { "id": "2" }
      ]
    },
  ]
},

我已经尝试使用函数 reduce(),但我不能,因为它不是一个对象,而是一个对象数组(类别)

      const group = data.reduce((r, array) => {
        r[array.categoria.id] = [...r[array.categoria.id] || [], array];
        return r;
      }, {});

有人可以帮帮我吗?

【问题讨论】:

  • reduce() 的参数是一个数组,所以我不明白你为什么不能使用它。
  • “我试过...”请提供尝试
  • @Barmar 对不起,我编辑了

标签: javascript arrays json sorting object


【解决方案1】:

您可以将对象按id 分组。在 reduce 内部,categoria 也被迭代以获得所需的id

var data = [{ nome: "jose", categoria: [{ id: "1" }, { id: "3" }] }, { nome: "maria", categoria: [{ id: "2" }] }, { nome: "pedro", categoria: [{ id: "1" }] }],
    result = Object.values(data.reduce((r, o) => {
        o.categoria.forEach(({ id }) => {
            if (!r[id]) r[id] = { id, pessoas: [] };
            r[id].pessoas.push(o);
        });
        return r;
    }, {}));

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 2021-02-18
    • 2012-05-02
    • 2021-08-13
    • 1970-01-01
    • 2012-06-22
    相关资源
    最近更新 更多