使用Ramda根据条件更新嵌套值

时间:2017-08-06 07:24:12

标签: javascript functional-programming ramda.js

我正在尝试使用Ramda更新嵌套对象结构中的数组中的值。

我想更新 this.setState({ counter: ++this.state.counter }); this.setState({ counter: --this.state.counter }); 中对象的值prop,名称为C

blah

我一直在镜头上玩,但看起来很啰嗦,我觉得我做错了。

理想情况下,我会喜欢能够返回新物体的东西。

const o = {
  A: {
    B: {
      C: [
        {name: 'blah', value: 'blah'},
        {name: 'vtha', value: 'blah'},
      ]
    }
  }
}

3 个答案:

答案 0 :(得分:2)

如果你想以不可变的方式去做,那就像

from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

iris = datasets.load_iris()

X = iris.data[:, [2,3]]
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)

sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)

lr = LogisticRegression(C = 1000, random_state=0)
lr.fit(X_train_std, y_train)
lr.coef_

Demo.

如果您想避免手动定义函数,可以用

替换映射函数
const fn = over(
  R.lensPath(['A', 'B', 'C']),
  R.map(
    o => o.name === 'blah' ? R.assoc('value', 'vtha', o): o
  )
)

但是imho三元运算符在这里看起来更具可读性。

答案 1 :(得分:1)

您可以尝试使用过滤器,我在下面写了一个例子。

const o = {
  A: {
    B: {
      C: [
        {name: 'blah', value: 'blah'},
        {name: 'vtha', value: 'blah'},
      ]
    }
  }
};

var pred = R.filter(R.where({name: R.contains('blah')}));

pred(o.A.B.C);

答案 2 :(得分:0)

要更新对象中的数组,我们需要数组的路径。然后,我们可以使用镜头和辅助功能adjustIfSatisfies

更新结果

const { propEq, identity, over, assoc, curry, lensPath, map, ifElse } = R
const o = {
  A: {
    B: {
      C: [
        {name: 'blah', value: 'blah'},
        {name: 'vtha', value: 'blah'},
      ]
    }
  }
}

const adjustIfSatisfies = curry(
  (pred, updateFn, samples) => {
    return map(ifElse(pred, updateFn, identity), samples)
  }
)

const result = over(
  lensPath(['A', 'B', 'C']), 
  adjustIfSatisfies(
    propEq('name', 'blah'), 
    assoc('value', 'vtha')
  ),
  o
)

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

相关问题