繁体   English   中英

Ramda:将键值数组转换为对象

[英]Ramda: convert key value array to object

我正在使用Ramda按键对规范化模型对象进行排序。 首先,我转换为关键|值对(相当于Object.entries )和排序使用的第一个值R.head (的key在对时的值)

我想将结果排序的对数组转换为对象数组 - 在示例代码中,我使用 ES6+ maparray destructuring

const data = {
  2: {name: 'two'},
  1: {name: 'one'}
}

const sortByKey = R.compose(R.sortBy(R.head), R.toPairs);
const sortedPairs = sortByKey(data)
console.log(sortedPairs)
// [["1",{"name":"one"}],["2",{"name":"two"}]]

const objs = sortedPairs.map(([key, value]) => {
  return {[key]: value}
})
console.log(objs)
// [{"1":{"name":"one"}},{"2":{"name":"two"}}]

我找不到Ramda函数的部分是

const objs = sortedPairs.map(([key, value]) => {
  return {[key]: value}
})

您可以将 R.map 与应用的 R.objOf 结合使用,将一对数组 ([key, value]) 转换为数组对象

 const { compose, map, apply, objOf, sortBy, head, toPairs } = R const sortByKey = compose(sortBy(head), toPairs) const arrayFromPairs = map(apply(objOf)) const data = { 2: {name: 'two'}, 1: {name: 'one'} } const result = arrayFromPairs(sortByKey(data)) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

您可以使用compose(fromPairs, of)从一对中创建一个对象。

const fromPair = compose(fromPairs, of);
fromPair(["a", 1]);
//=> {"a": 1}

 const { compose, fromPairs, head, map, of, sortBy, toPairs } = R; const sortByKey = compose(sortBy(head), toPairs); const fromPair = compose(fromPairs, of); const arrayFromPairs = map(fromPair); const data = { 2: {name: 'two'}, 1: {name: 'one'}, }; const sortedPairs = sortByKey(data); const objs = arrayFromPairs(sortedPairs); console.log(objs);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.min.js"></script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM