4

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,755
  • 3
  • 22
  • 27

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
  • 40,029
  • 7
  • 67
  • 77
  • 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
  • 129,518
  • 31
  • 228
  • 259
Colton
  • 218
  • 1
  • 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
  • 376,160
  • 25
  • 347
  • 392
  • @Timo, you need kind of access to the values. by using forEach, you need to declare an array and push the pairs to it. but why? – Nina Scholz Jul 22 '22 at 15:18