javascript - 使用javascript更新foreach循环中的数组对象

我正在尝试创建一个新数组。 我有不同版本的插件列表,我需要找到具有相同 uniqueIdentifier 但版本不同的插件,并从中创建一个数组。 示例:

  {
    "uniqueIdentifier": "theme_test",
    "version": "2011120800"
  },
  {
    "uniqueIdentifier": "theme_test",
    "version": "3011120800"
  },
  {
    "uniqueIdentifier": "theme_test",
    "version": "4011120800"
  },

变成这样:

{
    "uniqueIdentifier": "theme_test",
    "version": [
      "2011120800",
      "3011120800",
      "4011120800"
    ]
}

因此,在我的代码中我获得了所有信息,但我无法将此版本存储为数组。所以我正在检查 uniqueIdentifier 然后是版本,并尝试生成新数组:

item.pluginVersions.items.forEach(function(plugin) {
  pluginVersionsSupported.forEach(function(supportedPlugin) {
    if (plugin.uniqueIdentifier === supportedPlugin.uniqueIdentifier) {
      if (plugin.version == supportedPlugin.version) {
        pluginData = {
          uniqueIdentifier: plugin.uniqueIdentifier,
          version: []// need to update this to be an array
        }
      }
    }
  })

感谢所有帮助。

最佳答案

你需要使用Array.reduce方法:

const data = 
  [ { uniqueIdentifier: 'theme_test', version: '2011120800' } 
  , { uniqueIdentifier: 'theme_test', version: '3011120800' } 
  , { uniqueIdentifier: 'theme_test', version: '4011120800' } 
  ] 
const result = Object.values(data.reduce( (r,{uniqueIdentifier,version}) =>
  {
  r[uniqueIdentifier] ??= { uniqueIdentifier, version:[] }
  r[uniqueIdentifier].version.push(version)
  return r
  },{}))

console.log(result)

https://stackoverflow.com/questions/71574382/

相关文章:

javascript - 现代 Javascript 中的闭包 VS 类

flutter - 如何在 Flutter App 上设置自定义图片图标?使用应用图标

r - 使用逗号分隔的长度不等的数字字符串对多列进行数学运算

javascript - 如果其中没有图像, block 就会消失

visual-studio - Visual Studio 2022 无法添加服务引用且没有程序集引

typescript - 修改后的模板字面量类型

ASP.NET Core 6 - 从 swagger explorer 中隐藏最小的 api 端点

rust - 为什么在堆栈中分配的值不会导致双自由指针?

python - 如何将字典的键值对收集到 Python 中的一个大字典中?

r - 根据字符串匹配过滤列表