减少将数组转换为唯一的数组属性

时间:2019-08-31 07:29:42

标签: javascript ecmascript-6

如何使用reduce进行转换

[ { type: [ 'apple', 'google' ], currency: 'usd' }, 
  { type: [ 'apple', 'huawei' ], currency: 'eur' }, 
   ] 

[{
  type: 'apple',
  currency: ['usd','eur']
}, {
  type: 'google',
  currency: ['usd']
}, {
  type: 'huawei',
  currency: ['eur']
}]

除了一个reduce函数外,我是否还需要使用其他任何东西?我努力将数组类型转换为属性类型。

1 个答案:

答案 0 :(得分:2)

一种方法将Object.values()Array#reduce()结合使用以根据需要转换数据。

在这里,.reduce()用于建立将公司“类型”与存储“货币”字符串的数组相关的映射。获得该映射后,将其传递到Object.values(),后者将映射的值提取到数组中:

const input = [{
    type: ['apple', 'google'],
    currency: 'usd'
  },  
  {
    type: ['apple', 'huawei'],
    currency: 'eur'
  },  
];

/* Transform the mapping that is build to an array of values for
that mapping */
const output = Object.values(input.reduce((map, item) => {

  item.type.forEach(type => {

    /* Fetch or create a new "value" that contains the type and
       currency array for the current company type being iterated */
    const value = map[type] || {
      type: type,
      currency: []
    };
    
    /* Add the currency of the current item to the currency array
    of the mapped value being updated */
    value.currency.push(item.currency);

    map[type] = value;
  });

  return map;
}, {}))

console.log(output)