I’m trying to turn:
Array(19) [
{ category: 'Entertainment', 'Hang with Friends': 100 },
{ category: 'Entertainment', Chill: 30 },
{ category: 'Health', Yoga: 40 },
{ category: 'Health', Birthday: 200 },
]
into:
Array(19) [
{ category: 'Entertainment', 'Hang with Friends': 100, Chill: 30 },
{ category: 'Health', Yoga: 40, Birthday: 200 },
]
I attempted to do it using the logic from my last question but that one was reduced based on a prop that was a number, so I could index it. Here, I’m trying to do it based off of the category prop which is a string and can’t be used to index.
I tried the following, but it doesn’t work at all:
const reducedData = Object.values(newData).reduce(
(index, { id, category, subCategory, price }) => {
Object.assign((index[category] ??= category), {
[subCategory]: price,
});
return index;
},
{}
);
I want to be able to loop through the other objects in the array to find the obj with the correct category prop but I’m not sure how to do that.
Any help would be great!
Also, I’ve changed the format to the following because it was mentioned that it’s easier to work with. How would you the same to the following?
Array(19) [
{ category: 'Entertainment', subCategory: 'Hang with Friends', price: 100 },
{ category: 'Entertainment', subCategory: 'Chill', price: 30 },
{ category: 'Health', subCategory: 'Yoga', price: 40 },
{ category: 'Health', subCategory: 'Birthday', price: 200 },
]
2
Answers
You can use
Array#reduce
with an object that stores the merged object using the category as the key.You can use a type assertion for the accumulator in TypeScript:
Or you can set the generic type parameter for
reduce
: