如何 build/transform 上一个对象中的一个对象

How to build/transform an object from a previous object

我正在尝试根据我拥有的数据以特定结构创建一个对象。 来自:

// example #1
const dataGender = {"male": 30, "female": 70}

// example #2
const dataFruits = {"apple": 10, "banana": 20, "strawberry": 200}

至:

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"}
        }
    ]
}

换句话说,接受 dataGender 和 returns resultGender 以及 dataFruits.

的函数

从上面可以看出,结构是一致的,唯一变化的是键"value""en".

下的值

我找到了 ramdaobjOf(),这让我很接近:

const R = require("ramda")

const buildObject = R.compose(
  R.objOf("data"),
  R.map(R.objOf("value"))
);
buildObject([30, 70]); // => {"data": [{"value": 30}, {"value": 70}]}

但我仍然不知道如何在 "en" 下构建文本部分。

将对象转换为 [key, value] 对,并使用 R.applySpec 将它们映射到新对象。使用 R.nth 从对中获取键或值。使用 R.objOf 将数组嵌套在 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>

主要行为是获取一个对象,将其转换成对,然后将规范应用于每一对。我们可以将其提取为一个函数(mapSpec),然后用它构建特定的函数:

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>