typescript 如何将数组中的对象转换为像键一样合并?[关闭]

qxgroojn  于 2023-04-22  发布在  TypeScript
关注(0)|答案(1)|浏览(152)

已关闭,该问题需要details or clarity,目前不接受回答。
**想要改进此问题?**通过editing this post添加详细信息并澄清问题。

7天前关闭
Improve this question
我有一个对象数组,有3个字段日期,键和类型,type字段是practicetheory
结果
1.按key对阵列进行分组
1.转换数组:在新数组中,practice类型的对象应该在偶数索引中,theory类型的对象应该在奇数索引中。(如果我的解释不清楚,请检查输入和输出)
下面是我的代码,但它在transform the array中并不像预期的那样工作。

const input = [
  { key: 'A', type: 'practice' },
  { key: 'A', type: 'practice' },
  { key: 'A', type: 'theory' },
  { key: 'A', type: 'theory' },

  { key: 'B', type: 'practice' },
  { key: 'B', type: 'theory' },
  { key: 'B', type: 'practice' },

  { key: 'C', type: 'practice' },
  { key: 'C', type: 'theory' },
  { key: 'C', type: 'practice' },
]

function transformArray(arr) {
  const grouped = arr.reduce((result, item) => {
    const key = item.key;
    if (!result[key]) {
      result[key] = { key, values: [] };
    }
    result[key].values.push(item);
    return result;
  }, {});

  for (const group in grouped) {
    const values = grouped[group].values;
    const newValues = [];
    for (let i = 0; i < values.length; i++) {
      const item = values[i];
      if (item.type === 'practice' && i % 2 === 0) {
        newValues.push(item);
      } else if (item.type === 'theory' && i % 2 === 1) {
        newValues.push(item);
      }
    }
    grouped[group].values = newValues;
  }

  return Object.values(grouped);
}

console.log(transformArray(input));

预期输出:

[
  {
    key: 'A',
    values: [
      { key: 'A', type: 'practice', date: '2022-04-01' },  // index = even ==> practice
      { key: 'A', type: 'theory', date: '2022-04-10' },    // index = odd ==> theory
      { key: 'A', type: 'practice', date: '2022-04-07' }, // index = even ==> practice
      { key: 'A', type: 'theory', date: '2022-04-04' }, // index = odd ==> theory
    ],
  },
  {
    key: 'B',
    values: [
      { key: 'B', type: 'practice', date: '2022-04-05' },
      { key: 'B', type: 'theory', date: '2022-04-02' },
      { key: 'B', type: 'practice', date: '2022-04-08' },
    ],
  },
  {
    key: 'C',
    values: [
      { key: 'C', type: 'practice', date: '2022-04-03' },
      { key: 'C', type: 'theory', date: '2022-04-06' },
      { key: 'C', type: 'practice', date: '2022-04-09' },
    ],
  },
]
r7knjye2

r7knjye21#

您可以进行迭代,直到为对象找到一个空槽。

const
    input = [{ key: 'A', type: 'practice' }, { key: 'A', type: 'practice' }, { key: 'A', type: 'theory' }, { key: 'A', type: 'theory' }, { key: 'B', type: 'practice' }, { key: 'B', type: 'theory' }, { key: 'B', type: 'practice' }, { key: 'C', type: 'practice' }, { key: 'C', type: 'theory' }, { key: 'C', type: 'practice' }],
    result = Object.values(input.reduce((r, o) => {
        r[o.key] ??= [];
        let i = +(o.type === 'theory');
        while (r[o.key][i]) i += 2;
        r[o.key][i] = o;
        return r;
    }, {}));

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

相关问题