Ramdajs keyBy相当于lodash

我有一个数组,我想转换成一个对象。例如:Ramdajs keyBy相当于lodash

const arr = [{id: 1, key: ''}, {id: 2, key: ''}]; 

我想要得到的结果是:

const object = { 1: {id: 1, key: ''}, 2: { id: 2, key: ''}} 

随着lodash我可以使用keyBy功能,但我与ramda的工作,并没有发现有这个功能。

回答:

你可以用非常基本的功能,减少解决这个问题。

function keyBy(entities, id = "id") { 

entities.reduce((acc, entity) => {

acc[entity[id]] = entity;

return acc;

}, {});

}

回答:

最优雅的方式我可以ramda得到这样的:

const arr = [{id: 1, key: '1'}, {id: 2, key: '1'}, {id: 2, key: '2'}]; 

const reduceToIds = R.reduceBy(R.nthArg(1), [], R.prop('id'));

reduceToIds(arr);

REPL http://ramdajs.com/repl/#?const%20arr%20%3D%20%5B%7Bid%3A%201%2C%20key%3A%20%271%27%7D%2C%20%7Bid%3A%202%2C%20key%3A%20%271%27%7D%2C%20%7Bid%3A%202%2C%20key%3A%20%272%27%7D%5D%3B%0Aconst%20reduceToIds%20%3D%20R.reduceBy%28R.nthArg%281%29%2C%20%5B%5D%2C%20R.prop%28%27id%27%29%29%3B%0A%0AreduceToIds%28arr%29%3B

以上是 Ramdajs keyBy相当于lodash 的全部内容, 来源链接: utcz.com/qa/266502.html

回到顶部