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

用户2983988849

我正在尝试创建一个新数组。我有不同版本的插件列表,我需要找到具有相同 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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章