This is probably a 2 liner, but for some reason I have hit a wall.
I'd like to convert an array of objects to an object of key-value pairs.
So this:
var items = [
{
name: 'hello',
value: ['one', 'two']
},
{
name: 'hi',
value: ['one', 'two', 'three']
}
]
to this:
var items = {
'hello': ['one', 'two'],
'hi': ['one', 'two', 'three']
}
Is this really the most elegant way?
const newObj = {};
items.forEach((item) => {
newObj[item.name] = item.value;
});
I'd like to use ES6 arrow functions preferably. Also, can someone tell me if you think it would be easier to manipulate this data in the first or second format? For context, I am trying to teach myself topological sorts.
I would do that with Array.prototype.reduce()
, it is even more concise and certainly faster than Object.fromEntries()
:
const items = [{name:'hello',value:['one','two']},{name:'hi',value:['one','two','three']}],
result = items.reduce((r,{name,value}) => (r[name]=value,r), {})
console.log(result)
.as-console-wrapper{min-height:100%;}
A more concise method would be to use Object.fromEntries
:
var items = [
{
name: 'hello',
value: ['one', 'two']
},
{
name: 'hi',
value: ['one', 'two', 'three']
}
];
const newObj = Object.fromEntries(
items.map(({ name, value }) => [name, value])
);
console.log(newObj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With