在Ramda中有条件地添加和重命名属性,而不使用镜头

时间:2017-05-05 12:28:30

标签: javascript ramda.js

我需要修复ramda.js中对象的属性。我不想使用镜头。

我需要以下数据:

如果ab中的数组属性中的对象是其他

  • 没有属性“animationTimingFunction”使用值ease添加属性键“缓动”

  • 有属性“animationTimingFunction”将此属性重命名为“easing”并保持该值不变。

输入数据:

let data = {
    "a": [{
        "opacity": "1",
        "offset": "0"
    }, {
        "opacity": "0",
        "offset": "0.25",
        "animationTimingFunction": "linear"
    }, {
        "opacity": "1",
        "offset": "0.5"
    },
    "b": [{
        "transform": "scale3d(1, 1, 1)",
        "offset": "0"
    }, {
        "transform": "scale3d(1.05, 1.05, 1.05)",
        "offset": "0.5"
    }, {
        "transform": "scale3d(1, 1, 1)",
        "offset": "1"
    }]
};

输出应为:

let data = {
    "a": [{
        "opacity": "1",
        "offset": "0",
        "easing": "ease"
    }, {
        "opacity": "0",
        "offset": "0.25",
        "easing": "linear"
    }, {
        "opacity": "1",
        "offset": "0.5",
        "easing": "ease"
    },
    "b": [{
        "transform": "scale3d(1, 1, 1)",
        "offset": "0",
        "easing": "ease"
    }, {
        "transform": "scale3d(1.05, 1.05, 1.05)",
        "offset": "0.5",
        "easing": "ease"
    }, {
        "transform": "scale3d(1, 1, 1)",
        "offset": "1",
        "easing": "ease"
    }]
};

作为一个开始,我尝试过,但我想念条件部分:

    let convertEasing = (data) =>{
        let convert = data => R.assoc('easing', 'linear');
        let result = R.map(R.map(convert(data)), data)
        return result;
    };

1 个答案:

答案 0 :(得分:2)

如何

const alter = obj => {
  const ease = prop('animationTimingFunction', obj) || 'ease';
  return dissoc('animationTimingFunction', assoc('easing', ease, obj));
}

map(map(alter))(data);

如果您选择:

,您可以免费点数
const alter = pipe(
  chain(
    assoc('easing'),
    pipe(prop('animationTimingFunction'), defaultTo('ease')),
  ),
  dissoc('animationTimingFunction')
)

但在我看来,它的可读性会下降。

您可以在Ramda REPL上看到either version