Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update array object in foreach loop with javascript

I am trying to create a new array.
I have list of plugins with different versions, and I need to find plugins with same uniqueIdentifier but different versions, and create one array out of it.
Example:

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

to be like this:

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

So, in my code I am getting all the information, but I cannot make it work to store this versions as an array. So I am checking the uniqueIdentifier and then the version, and trying to generate new array:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
        }
      }
    }
  })

I appreciate all the help.

>Solution :

you need to use Array.reduce method:

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading