Home > Mobile >  Update array object in foreach loop with javascript
Update array object in foreach loop with javascript

Time:03-23

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:

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.

CodePudding user response:

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)

CodePudding user response:

Assuming you only have one pluginData: move the new object out of the loop so that it doesn't get created repeatedly, and in the loop push the version to the existing array.

pluginData = {
  uniqueIdentifier: plugin.uniqueIdentifier,
  version: []
}
item.pluginVersions.items.forEach(function(plugin) {
  ...
      if (plugin.version == supportedPlugin.version) {
        pluginData.version.push(plugin.version);

CodePudding user response:

You may also use Array#reduce() and Object.entries() as follows:

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

  • Related