-2

给定一个具有一些常见属性的对象数组,例如foosWithBar,如何在barsWithFoos不使用 lodash 之类的库的情况下创建另一个按这些常见属性分组的对象数组?我找到了创建按 key 分组的对象的示例reduce(),但这并不是我想要的。

const foosWithBar = [
  {
    id: 'Foo A',
    bar: {
      id: 'Bar 1',
    },
  },
  {
    id: 'Foo B',
    bar: {
      id: 'Bar 1',
    },
  },
  {
    id: 'Foo C',
    bar: {
      id: 'Bar 2',
    },
  },
  {
    id: 'Foo D',
    bar: {
      id: 'Bar 2',
    },
  },
]

const barsWithFoos = [
  {
    id: 'Bar 1',
    foos: [
      {
        id: 'Foo A',
      },
      {
        id: 'Foo B',
      },
    ],
  },
  {
    id: 'Bar 2',
    foos: [
      {
        id: 'Foo C',
      },
      {
        id: 'Foo D',
      },
    ],
  },
]
4

2 回答 2

1

迭代每个foo项目并在barsWithFoos数组中搜索它。如果不存在,则需要将其包含在barsWithFoos.push({ id: foo.bar.id, foos: [] }). 然后只需将列表推foo入:barbarsWithFoos[i - 1].foos.push({ id: foo.id })

const foosWithBar = [  {id: 'Foo A',bar: { id: 'Bar 1', }, }, {    id: 'Foo B',    bar: {      id: 'Bar 1',    },  },  {    id: 'Foo C',   bar: {      id: 'Bar 2',    },  },  {   id: 'Foo D',   bar: {      id: 'Bar 2',    },  },];

const barsWithFoos = [];
foosWithBar.forEach(foo => {
  const i = barsWithFoos.findIndex(bar => bar.id === foo.bar.id) + 1 
            || barsWithFoos.push({ id:  foo.bar.id, foos: [] });
  barsWithFoos[i - 1].foos.push({ id: foo.id });
})

console.log(barsWithFoos);

于 2021-08-17T16:29:53.973 回答
1

使用 reduce 将其转换为新格式。使用对象来跟踪您已经引用的“条”。您比使用 Object.values 来获取您的数组。

const foosWithBar = [
  { id: 'Foo A', bar: { id: 'Bar 1', }, },
  { id: 'Foo B', bar: { id: 'Bar 1', }, },
  { id: 'Foo C', bar: { id: 'Bar 2', }, },
  { id: 'Foo D', bar: { id: 'Bar 2', }, },
];

const opposite = Object.values(
  foosWithBar.reduce(
    function(acc, item) {
      if (!acc[item.bar.id]) { // have we seen it yet?
        acc[item.bar.id] = { // if not create the object
          id: item.bar.id,
          foos: [{
            id: item.id
          }]
        };
      } else { // if we seen it, just add the new foo
        acc[item.bar.id].foos.push({
            id: item.id
        });
      }
      return acc;
    }, {})
);
console.log(opposite);

于 2021-08-17T16:35:28.443 回答