I'm trying to create an object in a certain structure from data that I have. From:
// example #1
const dataGender = {"male": 30, "female": 70}
// example #2
const dataFruits = {"apple": 10, "banana": 20, "strawberry": 200}
to:
const resultGender = {
"data": [
{
"value": 30, "label": { "en": "male"}
},
{
"value": 70, "label": { "en": "female"}
}
]
}
const resultFruits = {
"data": [
{
"value": 30, "label": { "en": "apple"}
},
{
"value": 20, "label": { "en": "banana"}
},
{
"value": 200, "label": { "en": "strawberry"}
}
]
}
In other words, a function that accepts dataGender and returns resultGender, and likewise for dataFruits.
As can be seen above, the structure is consistent, and the only changes are to the values under keys "value" and "en".
I found ramda's objOf() which brings me close:
const R = require("ramda")
const buildObject = R.compose(
R.objOf("data"),
R.map(R.objOf("value"))
);
buildObject([30, 70]); // => {"data": [{"value": 30}, {"value": 70}]}
But I'm still missing how to build the textual part under "en".
Convert the object to pairs of [key, value], and map them to a new object using R.applySpec. Use R.nth to take the key or value from the pair. Use R.objOf to nest the array under data.
const { pipe, toPairs, map, applySpec, nth, objOf } = R
const fn = pipe(
toPairs,
map(applySpec({
value: nth(1),
label: {
en: nth(0)
}
})),
objOf('data')
)
// example #1
const dataGender = {"male": 30, "female": 70}
// example #2
const dataFruits = {"apple": 10, "banana": 20, "strawberry": 200}
console.log(fn(dataGender))
console.log(fn(dataFruits))
.as-console-wrapper {max-height: 100% !important; top: 0}
<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>
The main behavior is taking an object, converting it pairs, and then applying a spec to each pair. We can extract this to a function (mapSpec), and then build are specific function with it:
const { curry, map, toPairs, applySpec, pipe, nth, objOf } = R
const mapSpec = curry((spec, obj) => map(
applySpec(spec),
toPairs(obj)
))
const fn = pipe(
mapSpec({
value: nth(1),
label: {
en: nth(0)
}
}),
objOf('data')
)
// example #1
const dataGender = {"male": 30, "female": 70}
// example #2
const dataFruits = {"apple": 10, "banana": 20, "strawberry": 200}
console.log(fn(dataGender))
console.log(fn(dataFruits))
.as-console-wrapper {max-height: 100% !important; top: 0}
<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>