I'm trying to organize an array of objects by a specific value and use that value as a key for the rest of the object values. Here's an example:
{
0: {prize: "Foo", first_name: "John", last_name: "Smith"},
1: {prize: "Foo", first_name: "Mary", last_name: "Smith"},
2: {prize: "Bar", first_name: "Jane", last_name: "Doe"},
3: {prize: "Bar", first_name: "Jack", last_name: "Jones"},
4: {prize: "Foo", first_name: "Judy", last_name: "Alvarez"}
}
The desired outcome is this structure:
{
Foo: [
{first_name: "John", last_name: "Smith"},
{first_name: "Mary", last_name: "Smith"},
{first_name: "Judy", last_name: "Alvarez"}
],
Bar: [
{first_name: "Jane", last_name: "Doe"},
{first_name: "Jack", last_name: "Jones"}
]
}
I tried using TypeScript with a code snippet I found, but it didn't get me exactly what I needed:
console.log(
_.chain(res.data)
.groupBy("prize")
.map((value: any, key: any) => ({prize: key, winners: value}))
.value()
);
How can I adjust my code to achieve the desired format effectively? Is there a different approach I should take?
This seems like a common issue that may have been addressed before, but I'm having trouble articulating my problem in searches. Apologies if this is a duplicate question.