首页 > 解决方案 > 我需要帮助来合并对象数组中的值 - Javascript

问题描述

我正在处理一个项目,我将数据作为对象数组传给我,我需要将相同的键组合在一个键中并将值作为字符串数组。

这是我拥有的数据:

 inputArray = [
    {
      colors: 'Red',
      size: 'Small'
    },
    {
      colors: 'Blue',
      size: 'Large'
    },
    {
      colors: 'Red',
      size: 'Large'
    },
    {
      colors: 'Pink',
      size: 'X-Large'
    }
  ]

这是所需的输出:

 outputArray = {
    colors: ['Red','Blue','Pink'],
    size: ['Large','X-large','Small']
  }

标签: javascripttypescript

解决方案


您可以使用简单的字典结构来执行此操作。并在将其添加到数组之前验证每个元素是否已经存在。

const outputArray = {
  colors: [],
  size: [],
};

for (elem of inputArray) {
  if (!outputArray['colors'].includes(elem.colors)) {
    outputArray['colors'].push(elem.colors);
  }

  if (!outputArray['size'].includes(elem.size)) {
    outputArray['size'].push(elem.size);
  }
}

这会给

{
   colors: [ 'Red', 'Blue', 'Pink' ],
   size: [ 'Small', 'Large', 'X-Large' ]
}

推荐阅读