Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.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
Node.js 在Typescript中嵌套键的对象的组数组_Node.js_Typescript - Fatal编程技术网

Node.js 在Typescript中嵌套键的对象的组数组

Node.js 在Typescript中嵌套键的对象的组数组,node.js,typescript,Node.js,Typescript,我有一个对象数组,其中这些对象可以具有相同的名称,每个对象都有一个作为数组的错误键 const array = [ { name: 'Rafael', errors: [ 1, 2 ] }, { name: 'Rafael', errors: [7] }, { name: 'Joao', errors: [ 8 ] } ] 我试图得到这样的回答: const response = [ { name: 'Rafa

我有一个对象数组,其中这些对象可以具有相同的名称,每个对象都有一个作为数组的错误键

const array = [
  {
    name: 'Rafael',
    errors: [ 1, 2 ]
  },
  {
    name: 'Rafael',
    errors: [7]
  },
  {
    name: 'Joao',
    errors: [ 8 ]
  }
]
我试图得到这样的回答:

const response = [
  {
    name: 'Rafael',
    errors: [ 1, 2, 7]
  }, {
    name: 'Joao',
    errors: [8]
  }
]
有人知道怎么做吗?我尝试使用lodash的groupBy,但我无法得到响应,我想你可以用一个简单的而不是lodash,如下所示:

const array = [
  {
    name: 'Rafael',
    errors: [ 1, 2 ]
  },
  {
    name: 'Rafael',
    errors: [7]
  },
  {
    name: 'Joao',
    errors: [ 8 ]
  }
]

const newArray = array.reduce((list, item) => {
    const {name, errors} = item;
  const nameIndex = list.findIndex(item => item.name === name);
  if(nameIndex === -1){
    list.push(item);
  } else {
    list[nameIndex].errors.push(errors)
  }
  return list
}, []);
你也可以在家里试试