Change array in javascript into simpler object




arrays (3)

I have a simple JSON with an array that contains further objects, etc. like this:

languagePack:
[
  {
    'key': 'Username',
    'value': 'Benutzername',
    'group': 'default'
  },
  {
    'key': 'Password',
    'value': 'Passwort',
    'group': 'default'
  }
]

But what I really want is an object like this:

languagePack: 
{
    'Username': 'Benutzername',
    'Password': 'Passwort'
}

So, I want to reduce the array to simple key-value-pairs that are inside an array or even an object (keys are unique). Does anyone have an idea how to reduce this with some of these cool array functions? I only came up with something like an for each and building the object "by hand" property for property, but I remember there were some cool things for array like 'reduce', the spread operator (...), map, every, some, etc.

I tried it with something like:

var temp = this.languagePack.map(([key, value]) => ({key,value}))
console.log(temp)

But that only got me an error message TypeError: Invalid attempt to destructure non-iterable instance

Edit: All three answers are working perfectly fine. Thanks.


Basically you need to use forEach instead of map function and then you can build that object to whatever key, value pair you want to keep.

Try this, it will solve your problem.

var temp = {};

this.languagePack.forEach(({key,value}) => {
    temp[key] = value
})

console.log(temp)

Note: Here we are not using map because we want to return object not an array, so, we can use reduce function here to do so, but I thought this would be simple and easy to understand what we want and what are we doing here.


You can use ES6 Map for that use Object.fromEntries to convert map back to Object .

For more information about Map

let languagePack=
[{
  'key': 'Username',
  'value': 'Benutzername',
  'group': 'default'
},
{
  'key': 'Password',
  'value': 'Passwort',
  'group': 'default'
}];

let map = new Map();

languagePack.forEach((val)=>{
  map.set(val.key, val.value);
})
languagePack = Object.fromEntries(map);
console.log(languagePack);


use with Array#map its create the key and value as object and Object.assign covert array value to object

const languagePack = [ { 'key': 'Username', 'value': 'Benutzername', 'group': 'default' }, { 'key': 'Password', 'value': 'Passwort', 'group': 'default' } ];

var res = Object.assign({},...languagePack.map(({key,value}) => ({[key]:value})))

console.log(res)





arrays