Reputation: 31
I have an array of objects:
const data = [
{id: 1, date: {month: {value: 6, label: "June"}, year: {value: 2022, label: "2022"}},
{id: 2, date: {month: {value: 7, label: "July"}, year: {value: 2022, label: "2022"}}
]
I need to map over the array and combine the values for the date so it would look like this:
const data = [
{id: 1, date: "June, 2022"},
{id: 2, date: "July, 2022"}
]
I would like to use Ramda. I can map over the array, however, I am not sure how to combine nested objects and make it a string.
Upvotes: 0
Views: 199
Reputation: 13
data.map((e) => {
const date = `${e.date.month.label}, ${e.date.year.label}`;
return {
id: e.id,
date: date,
};
});
This should work.
Upvotes: 1
Reputation: 191936
You can map the array to new object by evolving the date
to the new form:
const { map, evolve, pipe, props, pluck, join } = R
const fn = map(evolve({
date: pipe(
props(['month', 'year']), // get an array of month and year objects
pluck('label'), // extract the labels
join(', ') // join to a string
)
}))
const data = [
{id: 1, date: {month: {value: 6, label: "June"}, year: {value: 2022, label: "2022"}}},
{id: 2, date: {month: {value: 7, label: "July"}, year: {value: 2022, label: "2022"}}}
]
const result = fn(data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
And combined with the nice simplicity of Fishamble answer:
const { map, evolve } = R
const fn = map(evolve({
date: ({ month, year }) => `${month.label}, ${year.label}`
}))
const data = [
{id: 1, date: {month: {value: 6, label: "June"}, year: {value: 2022, label: "2022"}}},
{id: 2, date: {month: {value: 7, label: "July"}, year: {value: 2022, label: "2022"}}}
]
const result = fn(data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Upvotes: 0