使用ramda.js

时间:2017-11-27 08:29:14

标签: javascript functional-programming ramda.js

我有一个数组:

var a = [
    {id: 1, val: 'a'},
    {id: 2, val: 'b'},
    {id: 3, val: 'c'},
    {id: 4, val: 'd'},
]

我希望将其转换为:

var b = {
    1: 'a',
    2: 'b',
    3: 'c',
    4: 'd',
}

其实我使用的是纯粹的js:

var b = a.reduce(
    (ac, pr) => ({
      ...ac,
      [pr.id]: pr.val,
    }),
    {}
  );

但也许Ramda.js为此目的有特别之处?

6 个答案:

答案 0 :(得分:0)



var a = [
    {id: 1, val: 'a'},
    {id: 2, val: 'b'},
    {id: 3, val: 'c'},
    {id: 4, val: 'd'},
]

var result = {};
for (var i=0; i<a.length; i++) {
  result[a[i].id] = a[i].val;
}

console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

通过使用R.props进行映射,从每个对象获取有序值,并使用R.fromPairs创建对象:

&#13;
&#13;
var a = [
    {id: 1, val: 'a'},
    {id: 2, val: 'b'},
    {id: 3, val: 'c'},
    {id: 4, val: 'd'},
];

var result = R.compose(R.fromPairs, R.map(R.props(['id', 'val'])));

console.log(result(a));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

最简单,没有意义的点

compose(fromPairs, map(values))(a)

const { compose, fromPairs, map, values } = R

const a = [
    {id: 1, val: 'a'},
    {id: 2, val: 'b'},
    {id: 3, val: 'c'},
    {id: 4, val: 'd'},
]

const result = compose(fromPairs, map(values))(a)

console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

答案 3 :(得分:0)

如果还有人经过这里,的确是这样:

R.indexBy(R.prop('id'), someArray);

See indexBy in Ramda's documentation

答案 4 :(得分:0)

这可能是最简单的方法:

pipe(map(props(['id', 'val'])), fromPairs)(a)

@spflow's answer 更简单,但不能保证适用于所有平台。 Ramda 代码高尔夫总是很有趣!

const { fromPairs, map, pipe, props } = R

const a = [
    {id: 1, val: 'a'},
    {id: 2, val: 'b'},
    {id: 3, val: 'c'},
    {id: 4, val: 'd'},
]

const result = pipe(map(props(['id', 'val'])), fromPairs)(a)

console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.min.js"></script>

答案 5 :(得分:0)

还有一种方法:

const { indexBy, prop, pipe, pluck } = R
const a = [
    {id: 1, val: 'a'},
    {id: 2, val: 'b'},
    {id: 3, val: 'c'},
    {id: 4, val: 'd'},
]
const result = pipe(indexBy(prop('id')), pluck('val'))(a)
console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.min.js"></script>