[英]change a prop in list of object in ramda.js
I have an array of object in JSON and want to change one value's properties. 我在JSON中有一个对象数组,想要更改一个值的属性。 for example assume I have a key field which is unique and
amount
, name
props. 例如,假设我有一个唯一的字段,
amount
name
, name
props。 my approach is to find an object in the list with findIndex
or map then remove it and make a new object and push to it. 我的方法是使用
findIndex
或map在列表中找到一个对象,然后将其删除并创建一个新对象并将其推入。 is this good way? 这是好方法吗? can recommend better approach or functions?
可以推荐更好的方法或功能?
Lenses
might be the canonical way to deal with this, although Ramda has a number of alternatives. 尽管Ramda有许多选择,但
Lenses
可能是解决这一问题的规范方法。
const people = [
{id: 1, name: 'fred', age: 28},
{id: 2, name: 'wilma', age: 25},
{id: 3, name: 'barney', age: 27},
{id: 4, name: 'betty', age: 29},
]
const personIdx = name => findIndex(propEq('name', name), people)
const ageLens = idx => lensPath([idx, 'age'])
const wLens = ageLens(personIdx('wilma'))
const newPeople = over(wLens, age => age + 1, people)
//=> [
// {id: 1, name: 'fred', age: 28},
// {id: 2, name: 'wilma', age: 26},
// {id: 3, name: 'barney', age: 27},
// {id: 4, name: 'betty', age: 29},
// ]
Note that although newPeople
is a brand new object, it shares as much as it can with the existing people
. 请注意,尽管
newPeople
是一个全新的对象,但它与现有people
共享尽可能多的共享。 For instance, newPeople[3] === people[3] //=> true
. 例如,
newPeople[3] === people[3] //=> true
。
Also note that as well as adjusting a parameter with this lens using over
, we could simply fetch the value using view
: 还要注意,除了使用
over
调整此镜头的参数外,我们还可以使用view
来简单地获取值:
view(wLens, people) //=> 25
Or we could set it to a fixed value with set
: 或者我们可以将其设置为一个固定值
set
:
set(wLens, 42, people) //=> new version of `people` with wilma's age at 42
Finally, note that lenses compose. 最后,请注意镜头组成。 We could have also written this:
我们也可以这样写:
const ageLens = idx => compose(lensIndex(idx), lensProp('age')).
Lens composition can be very powerful. 镜头组成非常强大。
You can see this in action on the Rand REPL . 您可以在Rand REPL上看到这一点。
Something like this maybe? 像这样的东西?
var org =
[
{name:"one",age:1}
,{name:"two",age:2}
]
;
var newArray =
org
.map(
(x,index)=>
index === 1
?Object.assign(
{}
,x
,{name:"new name"}
)
:x
)
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.