Estoy tratando de crear una nueva matriz. Tengo una lista de complementos con diferentes versiones, y necesito encontrar complementos con el mismo identificador único pero versiones diferentes, y crear una matriz a partir de él. Ejemplo:
{ "uniqueIdentifier": "theme_test", "version": "2011120800" }, { "uniqueIdentifier": "theme_test", "version": "3011120800" }, { "uniqueIdentifier": "theme_test", "version": "4011120800" },ser así:
{ "uniqueIdentifier": "theme_test", "version": [ "2011120800", "3011120800", "4011120800" ] }Entonces, en mi código obtengo toda la información, pero no puedo hacer que funcione para almacenar estas versiones como una matriz. Así que estoy revisando el identificador único y luego la versión, y tratando de generar una nueva matriz:
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 } } } })Yo aprecio toda la ayuda.
necesitas usar el método 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)Suponiendo que solo tiene un pluginData: mueva el nuevo objeto fuera del bucle para que no se cree repetidamente, y en el bucle empuje la versión a la matriz existente.
pluginData = { uniqueIdentifier: plugin.uniqueIdentifier, version: [] } item.pluginVersions.items.forEach(function(plugin) { ... if (plugin.version == supportedPlugin.version) { pluginData.version.push(plugin.version);También puede usar Array#reduce() y Object.entries() de la siguiente manera:
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 );