Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在typescript中转换数组_Typescript - Fatal编程技术网

如何在typescript中转换数组

如何在typescript中转换数组,typescript,Typescript,我有一个如下所示的数组: [ {productypeId:1,producsubiteid:1,productid:1}, {productypeId:1,producsubiteid:1,productid:2}, {productypeId:1,producsubiteid:2,productid:3}, {productypeId:1,producsubiteid:2,productid:4}, {productypeId:2,producsubiteid:5,productid:6},

我有一个如下所示的数组:

[
{productypeId:1,producsubiteid:1,productid:1},
{productypeId:1,producsubiteid:1,productid:2},
{productypeId:1,producsubiteid:2,productid:3},
{productypeId:1,producsubiteid:2,productid:4},
{productypeId:2,producsubiteid:5,productid:6},
{productypeId:2,producsubiteid:5,productid:7}
]
我想要以下输出:

[
{productypeId:1,producsubiteid:1,d:'1,2'},
{productypeId:1,producsubiteid:2,d:'3,4'},
{productypeId:2,producsubiteid:5,d:'6,7'}
]

请提前帮助我,谢谢

我从您的输出中看到了什么,我假设您尝试生成一个具有相同值的输出,该值为
productypeId
producsubiteid
productid
指定为重复值。这里是我使用数组reduce的解决方案。希望这能解决你的问题

interface InputItem {
  productypeId: number;
  producsubtypeId: number;
  productid: number;
}

interface OuputItem {
  productypeId: number;
  producsubtypeId: number;
  d: string;
}

const input: InputItem[] = [
  { productypeId: 1, producsubtypeId: 1, productid: 1 },
  { productypeId: 1, producsubtypeId: 1, productid: 2 },
  { productypeId: 1, producsubtypeId: 2, productid: 3 },
  { productypeId: 1, producsubtypeId: 2, productid: 4 },
  { productypeId: 2, producsubtypeId: 5, productid: 6 },
  { productypeId: 2, producsubtypeId: 5, productid: 7 }
];

const output = input.reduce((res, item) => {
  // destructuring input item
  const { productypeId, producsubtypeId, productid } = item;

  // find unique set by productypeId and producsubtypeId in accumulator 'res'
  const groupIndex = res.findIndex(
    i =>
      i.productypeId === productypeId && producsubtypeId === i.producsubtypeId
  );

  // if index exist in accumulator, we concat productid value as 'd'
  // else push a new unique set to accumulator
  if (groupIndex > -1) {
    res[groupIndex].d += `,${productid}`;
  } else {
    res.push({ productypeId, producsubtypeId, d: `${productid}` });
  }

  return res;
}, [] as OuputItem[]);

productTypeId
productSubTypeId
始终相同吗?即1。如果它们不一样,你想做什么?我已经更改了。你能看看并帮助我吗?你遇到问题的代码是什么?你的代码有什么问题?你收到错误信息了吗?错误消息是什么?你得到的结果不是你期望的结果吗?你期望得到什么样的结果?为什么?你会得到什么样的结果?两者有什么不同?你观察到的行为是否不是期望的行为?期望的行为是什么?为什么?观察到的行为是什么?它们有什么不同?请提供一个。我正在使用输入数组,并将第一个数组转换为typescript中的第二个数组,并保存在数据库中。我希望第二个数组已输出。我理解您现在正在尝试的操作。请正确格式化您的代码示例:请在这里编写代码,而不仅仅是在stackblitz上。