编程语言
首页 > 编程语言> > javascript-使用ramdajs将对象转换为对象数组

javascript-使用ramdajs将对象转换为对象数组

作者:互联网

我正在编写程序,计算文件中的单词数.

假设对象是这样的:

{
  I: 2,
  it: 4,
  that: 1
}

我想做到:

[
  { word: 'I', count: 2 }, 
  { word: 'it', count: 4 }, 
  { word: 'that', count: 1 }
]

我可以通过使用命令式编程来实现此目标:循环对象…

我检查了文档和谷歌,但找不到适合的任何方法:(

谢谢

解决方法:

可以使用R.toPairsR.zipObj来实现:

//    convert :: {a} -> [{ word :: String, count :: a }]
const convert = R.compose(R.map(R.zipObj(['word', 'count'])), R.toPairs);

convert({I: 2, it: 4, that: 1});
// => [{"count": 2, "word": "I"}, {"count": 4, "word": "it"}, {"count": 1, "word": "that"}]

标签:ramda-js,javascript,functional-programming
来源: https://codeday.me/bug/20191119/2035591.html