I have the following array
data = [
{ name: 'foo', type: 'fizz', val: 9 },
{ name: 'boo', type: 'buzz', val: 3 },
{ name: 'bar', type: 'fizz', val: 4 },
{ name: 'car', type: 'buzz', val: 7 },
];
How do I make it
{
9: 'foo',
3: 'boo,
4: 'bar',
7: 'car'
}
in ES6.
Thanks in advance!!
Using Array#forEach
.
var data = [ { name: 'foo', type: 'fizz', val: 9 }, { name: 'boo', type: 'buzz', val: 3 }, { name: 'bar', type: 'fizz', val: 4 }, { name: 'car', type: 'buzz', val: 7 }, ],
res = {};
data.forEach(v => res[v.val] = v.name);
console.log(res);
Using Array#reduce
.
var data = [ { name: 'foo', type: 'fizz', val: 9 }, { name: 'boo', type: 'buzz', val: 3 }, { name: 'bar', type: 'fizz', val: 4 }, { name: 'car', type: 'buzz', val: 7 }, ],
res = data.reduce(function(s,a){
s[a.val] = a.name;
return s;
}, {});
console.log(res);
Something like this should work:
const data = [
{ name: 'foo', type: 'fizz', val: 9 },
{ name: 'boo', type: 'buzz', val: 3 },
{ name: 'bar', type: 'fizz', val: 4 },
{ name: 'car', type: 'buzz', val: 7 },
];
const reduced = data.reduce((acc, item) => {
acc[item.val] = item.name;
return acc;
}, {});
console.log(reduced);
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