-2

I have data that looks like

[{"letter": "a", "word" : "apple"}, {"letter": "b", "word":"ball"}, {"letter": "a", "word":"alpha"}, {"letter": "c", "word":"cat"}]

and I want to transform it into

{"a":["apple", "alpha"], "b": ["ball"], "c":["cat"]}
Rob
  • 3
  • 2

3 Answers3

1

you can use a reduce function for this

const arr = [{"letter": "a", "word" : "apple"}, {"letter": "b", "word":"ball"}, {"letter": "a", "word":"alpha"}, {"letter": "c", "word":"cat"}]

const transformed = arr.reduce((acc, cur) => {
  acc[cur.letter] = acc[cur.letter] || [];
  acc[cur.letter].push(cur.word);
  return acc;
}, {});

console.log(transformed);
D. Seah
  • 4,472
  • 1
  • 12
  • 20
0

Something like this you mean?

const arr = [{"letter": "a", "word" : "apple"}, {"letter": "b", "word":"ball"}, {"letter": "a", "word":"alpha"}, {"letter": "c", "word":"cat"}];

let result = {};
for (let e of arr)
  (result[e.letter] = result[e.letter] || []).push(e.word);
  
console.log(result)
Pablo CG
  • 818
  • 6
  • 18
-1

Based on the updated outcome. Below is my approach

var elements = [{"letter": "a", "word" : "apple"}, {"letter": "b", "word":"ball"}, {"letter": "a", "word":"alpha"}, {"letter": "c", "word":"cat"}]

output = {}
elements.forEach(function(e){
    key = e['letter']
    value = e['word']
    if(output[key]){
        output[key] = [...output[key], value];
    }else{
        output[key] = [value];
    }
})

console.log(output);
Vikas Gupta
  • 65
  • 1
  • 5
  • This is not a good answer, and should have been posted as a comment (which I had done several minutes prior to this answer). You only need a couple more points of rep to be able to comment; please don't waste the rep getting downvoted on comments as answers. – Heretic Monkey May 21 '20 at 14:07
  • @HereticMonkey I do understand the platform ethics, I wanted to elaborate more on Why the requirement is invalid. As a new contributor myself, i understand sometime people face issues in fundamentals, which is why I took a step and tried to elaborate on the invalid requirement. – Vikas Gupta May 21 '20 at 14:21