7puns
7puns

Reputation: 1555

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?

Upvotes: 2

Views: 392

Answers (1)

michaelmesser
michaelmesser

Reputation: 3726

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)

Upvotes: 4

Related Questions