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

1

3 Answers 3

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);

4
  • 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
    Commented Mar 24, 2017 at 20:11
  • 1
    Yeah, someone's downvoting our valid answers xD Oh well...
    – Colton
    Commented Mar 24, 2017 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. Commented Mar 24, 2017 at 20:14
  • @Kinduser Thank you for your response!! It's not me who is down voting!! :( Commented Mar 24, 2017 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);

2
  • Instead of a codepen, you can insert a working snippet into your answer (see rightmost button on the toolbar when you edit).
    – trincot
    Commented Mar 24, 2017 at 20:13
  • Oh sweet, I was wondering how people did that, thanks!
    – Colton
    Commented Mar 24, 2017 at 20:14
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);

1
  • @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? Commented Jul 22, 2022 at 15:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.