gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:02:23 24 4
gpt4 key购买 nike

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

关于javascript - 使用javascript更新foreach循环中的数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71574382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com