Javascript - 为什么 Ramda over 函数在这里不起作用?
Javascript - Why is Ramda over function not working here?
我正在尝试使用键作为参考用另一个对象填充一个对象。
// Object with actual information
{
'key1.key2.key3': {},
'key1.key4': {},
}
// Desired Shape
{
'key1': {
'key2': {
'key3': {
},
},
'key4': {
},
}
使用 Ramda 库这应该是小菜一碟,与此同时,我成功地填充了具有所需形状的蓄能器,但我遇到的情况与我预期的不同。
const fillShapeWithParsed = shape =>
R.pipe(
R.toPairs,
R.reduce(
(accumulator, [shapeKey, complexValue]) => {
return R.over(
R.lensPath(shapeKey.split('.').filter(key => key !== '')),
R.merge(complexValue),
accumulator
);
},
shape
)
);
上面代码的输出是:如果带信息的对象中引用键的值是一个对象数组,则累加器接收转换成以索引为键的嵌套对象的值。
// Object with information
{
'key1.key2.key3': [
{},
{},
{},
],
}
// Desired Shape
{
'key1': {
'key2': {
'key3': {
'0': {},
'1': {},
'2': {},
},
},
},
}
此时我知道这是由 R.merge() 函数完成的...
所以我用 R.clone() 更改了它,它抛出了一个关于参数不是函数的错误。
除此之外,现在合并功能已被弃用,我想将其替换为有助于我不转换 complexValue
的东西
其实你离得并不远。我想你所缺少的只是检查 complexValue
是否是一个数组。如果是,就按原样 return (R.always
) 否则将其与 accumulator
.
合并
我还直接将 R.pipe
分配给了 fillShapeWithParsed
const input = {
'key1.key2.key3': {},
'key1.key4': {},
'key1.key4.key5': [
{},
{},
{},
],
};
const fillShapeWithParsed = R.pipe(
R.toPairs,
R.reduce(
(accumulator, [shapeKey, complexValue]) => {
return R.over(
R.lensPath(shapeKey.split('.').filter(key => key !== '')),
R.is(Array, complexValue) ? R.always(complexValue) : R.merge(complexValue),
accumulator
);
}, {})
);
console.log(
fillShapeWithParsed(input)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
我正在尝试使用键作为参考用另一个对象填充一个对象。
// Object with actual information
{
'key1.key2.key3': {},
'key1.key4': {},
}
// Desired Shape
{
'key1': {
'key2': {
'key3': {
},
},
'key4': {
},
}
使用 Ramda 库这应该是小菜一碟,与此同时,我成功地填充了具有所需形状的蓄能器,但我遇到的情况与我预期的不同。
const fillShapeWithParsed = shape =>
R.pipe(
R.toPairs,
R.reduce(
(accumulator, [shapeKey, complexValue]) => {
return R.over(
R.lensPath(shapeKey.split('.').filter(key => key !== '')),
R.merge(complexValue),
accumulator
);
},
shape
)
);
上面代码的输出是:如果带信息的对象中引用键的值是一个对象数组,则累加器接收转换成以索引为键的嵌套对象的值。
// Object with information
{
'key1.key2.key3': [
{},
{},
{},
],
}
// Desired Shape
{
'key1': {
'key2': {
'key3': {
'0': {},
'1': {},
'2': {},
},
},
},
}
此时我知道这是由 R.merge() 函数完成的...
所以我用 R.clone() 更改了它,它抛出了一个关于参数不是函数的错误。
除此之外,现在合并功能已被弃用,我想将其替换为有助于我不转换 complexValue
的东西其实你离得并不远。我想你所缺少的只是检查 complexValue
是否是一个数组。如果是,就按原样 return (R.always
) 否则将其与 accumulator
.
我还直接将 R.pipe
分配给了 fillShapeWithParsed
const input = {
'key1.key2.key3': {},
'key1.key4': {},
'key1.key4.key5': [
{},
{},
{},
],
};
const fillShapeWithParsed = R.pipe(
R.toPairs,
R.reduce(
(accumulator, [shapeKey, complexValue]) => {
return R.over(
R.lensPath(shapeKey.split('.').filter(key => key !== '')),
R.is(Array, complexValue) ? R.always(complexValue) : R.merge(complexValue),
accumulator
);
}, {})
);
console.log(
fillShapeWithParsed(input)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>