我正在嘗試創建一個新陣列。我有不同版本的插件串列,我需要找到具有相同 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
}
}
}
})
我感謝所有的幫助。
uj5u.com熱心網友回復:
你需要使用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)
uj5u.com熱心網友回復:
假設您只有一個 pluginData:將新物件移出回圈,使其不會重復創建,并在回圈中將版本推送到現有陣列。
pluginData = {
uniqueIdentifier: plugin.uniqueIdentifier,
version: []
}
item.pluginVersions.items.forEach(function(plugin) {
...
if (plugin.version == supportedPlugin.version) {
pluginData.version.push(plugin.version);
uj5u.com熱心網友回復:
你也可以使用Array#reduce()和Object.entries()如下:
const data = [{"uniqueIdentifier": "theme_test","version": "2011120800"},{"uniqueIdentifier": "theme_test","version": "3011120800"},{"uniqueIdentifier": "theme_test","version": "4011120800"}];
const groupedData = Object.entries(
data.reduce(
(prev, {uniqueIdentifier,version}) =>
({ ...prev, [uniqueIdentifier]:(prev[uniqueIdentifier] || []).concat(version) }), {}
)
)
.map(([uniqueIdentifier,version]) => ({uniqueIdentifier,version}));
console.log( groupedData );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/446732.html
標籤:javascript 数组
上一篇:調整視窗大小時,如何使鏈接保持相對于背景影像的位置?
下一篇:添加子元素時如何增加元素的高度?
