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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Yeah, someone's downvoting our valid answers xD Oh well...
@Colton Well, officially people are aloud to downvote for any reason at all, including when people give answers to zero-effort questions.
@Kinduser Thank you for your response!! It's not me who is down voting!! :(
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 Comments

Instead of a codepen, you can insert a working snippet into your answer (see rightmost button on the toolbar when you edit).
Oh sweet, I was wondering how people did that, thanks!
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 Comment

@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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.