在字符串数组中拆分项目(成键值对)并按公共键分组

In array of strings split items (into key-value pairs) and group by common key

我正在使用 Angular,我在以下结构中输入数据,键 = 字符串,值 = 字符串数组:

  inputObject= {
'employees': [
  'bob/january',
  'bob/january-february',
  'bob/january-march',
  'steve/january',
  'steve/january-february',
  'steve/january-march',
  'september',
],

};

我需要通过使用“/”作为分隔符拆分值来转换此对象,因此拆分员工数组中的字符串元素并将其放入新对象中,其中“/”之前的字符串值变为新对象的键和字符串中 '/'are added as an array of string values. if the value in the employees element does not have a '/' 之后的字符串值,那么键应该是硬编码的字符串值,例如 'n/a' 如下所示

期望的输出:

  outputObject = {
'bob': [
  'january',
  'january-february',
  'january-march'
],
'steve': [
  'january',
  'january-february',
  'january-march',
],
'n/a': 'september'

}

我尝试了各种技术,其中一个例子是我尝试添加到地图的代码片段。这可以通过添加到新对象或您可以推荐的任何其他数据结构来实现。

inputObject= {
    'employees': [
      'bob/january',
      'bob/january-february',
      'bob/january-march',
      'steve/january',
      'steve/january-february',
      'steve/january-march',
      'september',
    ],
  };

  let outputMap = new Map();
  
  let splitValues = inputObject.employees.map(a => a.split('/'));
   console.log(splitValues)
  
  splitValues.forEach(a => {
    if(a.length > 1){
    outputMap.set(a[0], a[1]);
    } else {
    outputMap.set('n/a', a[0])
    }
    
  });
  
  console.log(outputMap)

堆栈闪电战: https://stackblitz.com/edit/angular-ivy-ogbdwv

您可以使用Array.prototype.reduce() to group items and String.prototype.match()实现拆分逻辑:

const input = {
          employees: [
          'bob/january',
          'bob/january-february',
          'bob/january-march',
          'steve/january',
          'steve/january-february',
          'steve/january-march',
          'september',
        ]
      },
      
      
      output = input.employees
        .reduce((acc, str) => {
          const [key = 'n/a', value] = str
            .match(/(([^/]+)\/)?(.+)/)
            .slice(2)
          const group = acc[key]
          group
            ? group.push(value)
            : acc[key] = [value]
          return acc
        }, {})
      
console.log(output)
.as-console-wrapper{min-height:100%;}

Reduce 非常适合将一种数据结构更改为另一种数据结构。

它可能看起来像这样(未经测试):

type Output = {
  [name:string]: string[]
}

const output = inputObject.employees.reduce<Output>((acc, curr) => {
  const splitStr = curr.split('/')

  if (splitStr.length === 1) {
    return {
      ...acc,
      'n/a': [
        ...acc['n/a'],
        splitStr[0]
      ]
    }
  }

  const [name, date] = splitStr;

  return {
    ...acc,
    [name]: acc[name]?.length > 0
      ? [...acc[name], date]
      : [date]
  }
}, {});

console.log(output);