twenty twenty - 11 months ago 54
Javascript Question

Reduce array of objects to parameter with the same objects

I hope the title is enough self-explanatory but I will try to clarify with a fiddle I've created. There are two arrays, one called tags which is what I currently have and tags_ideal which is what I really want to achieve.

Current state:

var tags = [
{
id: 1,
color: 'red',
l10n: [
{
name: 'Something something',
lang: 'english'
},
{
name: 'Etwas etwas',
lang: 'deutsch'
}
]
},
{
id: 2,
color: 'blue',
l10n: ...
}
]


What I'm after:

var tags_ideal = [
{
id: 1,
color: 'red',
l10n: {
'english': {
name: 'Something something',
},
'deutsch': {
name: 'Etwas etwas',
}
}
},
{
id: 2,
color: 'blue',
l10n: ...
}
]


I have the first case and want to convert all the stuff from l10n so that they don't have a lang: english parameter but rather have an object called english and the name/title inside of that. Below both tags is what I tried to do and what works when I pass just the l10n object into it, but not the whole thing (I do understand why, and now I would like to know how to do what I am really after).

Also, please note that my arrays are not correct at this point. I have appended three dots at the start of the next object just to point out that there is more than one object in my array.

Here's the fiddle:
https://jsfiddle.net/cgvpuj70/

Answer Source

Use .reduce() on the l10n to make an object populated with the keys/values derived from each object in the current Array.

var tags = [
  {
    id: 1,
    color: 'red',
    l10n: [
      {
        name: 'Something something',
        lang: 'english'
      },
      {
        name: 'Etwas etwas',
        lang: 'deutsch'
      }
    ]
  },
  {
   id: 2,
   color: 'blue'
  }
]

tags.forEach(t => {
  t.l10n = t.l10n && t.l10n.reduce((o, data) => 
    Object.assign(o, {[data.lang]: {name: data.name}})
  , {})
})

console.log(tags);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download