简体   繁体   中英

Setting values of arrays of objects in ramdajs

This is for the ramdajs gurus around. Consider an array of objects, arr , in the code snippet shown below. To set the value of the first object, to say 6, using lenses, one would expect the result to be an array. However, this appears not the case but rather the result is an object. Example:

import R from 'ramda'
let arr = [{a: 1}, {a: 2}, {a: 3}]
let aLens = R.lensPath([0, 'a'])
let result = R.set(aLens, 6, arr)

Expected result:

[{a: 6}, {a: 2}, {a: 3}]

Actual result:

{0: {a: 6}, 1: {a: 2}, 2: {a: 3}}

One way to get back the expected array would be to extract the values from the object:

result = R.values(result)

Is there a better way to set a value in an array of objects so that the result is also an array?

Use lensIndex

import R from 'ramda'
let arr = [{a: 1}, {a: 2}, {a: 3}]
let aLens = R.compose(R.lensIndex(0), R.lensPath('a'))
let result = R.set(aLens, 6, arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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