Change array in javascript into simpler object
You can use the javascript reduce
function to create an empty object and put each key and value in it.
const data = [
{
'key': 'Username',
'value': 'Benutzername',
'group': 'default'
},
{
'key': 'Password',
'value': 'Passwort',
'group': 'default'
}
];
const newData = data.reduce((acc, row) => {
acc[row.key] = row.value;
return acc;
}, {});
console.log(newData);
Edit : Nice suggest of Donny Verduijn. You can use es6 destructuring to write the function shorter.
const newData = data.reduce((acc, { key, value }) => ({ ...acc, [key]: value }), {});
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.