3

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!!

Testaccount
  • 2,585
  • 3
  • 20
  • 24

3 Answers3

12

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);
kind user
  • 34,867
  • 6
  • 60
  • 74
  • Excuse me, looking forward for some details from the downvoter. If there's something wrong with my answer, tell me and I will improve it. – kind user Mar 24 '17 at 20:11
  • 1
    Yeah, someone's downvoting our valid answers xD Oh well... – Colton Mar 24 '17 at 20:12
  • 1
    @Colton Well, officially people are aloud to downvote for any reason at all, including when people give answers to zero-effort questions. – 4castle Mar 24 '17 at 20:14
  • @Kinduser Thank you for your response!! It's not me who is down voting!! :( – Testaccount Mar 24 '17 at 20:15
2

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);
Mulan
  • 119,326
  • 28
  • 214
  • 246
Colton
  • 208
  • 2
  • 10
1

You could use Object.fromEntries and map arrays with all key/value pairs.

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 }],
    object = Object.fromEntries(data.map(({ val, name }) => [val, name]));

console.log(object);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358