cons columnDefs = [
{
label: 'The_First_Name',
value: getProp,
args: ['firstName'] // different number of arguments depending on function
},
{
label: 'City',
value: getNestedProperty,
args: ['location', 'city']
}
]
const data = [
{
firstName: 'Joe',
lastName: 'Smith',
location: {
city: 'London'
}
},
{
firstName: 'Anna',
lastName: 'Andersson',
location: {
city: 'Stockholm'
}
}
]
const getProp = (object, key) => R.prop(key, object);
const getNestedProperty = (obj, args) => R.path(..args, obj);
Ramda管道映射数据:
const tableBuilder = R.pipe(R.map); // some ramda functions in here
const rows = tableBuilder(data, columnDefs);
所需的输出:
rows output:
[
{
The_First_Name: 'Joe',
city: 'London'
},
{
The_First_Name: 'Anna',
city: 'Stockholm'
}
]
每行的键是
label
中的columnDefs
属性。该值与Ramda
道具中定义的自变量一起从value
道具中的args
函数获取。https://plnkr.co/edit/rOGh4zkyOEF24TLaCZ4e?p=preview
完全卡住了。 Ramda甚至可能做到这一点吗?还是最好用纯JavaScript做到这一点?
最佳答案
您可以使用applySpec
从另一个对象创建一个对象:
const obj = applySpec({
The_First_Name: prop('firstName'),
city: path(['location', 'city'])
})
obj({
firstName: 'Joe',
lastName: 'Smith',
location: {
city: 'London'
}
});
//=> {"The_First_Name": "Joe", "city": "London"}
然后,您可以使用该函数在数组上进行映射:
const data = [
{
firstName: 'Joe',
lastName: 'Smith',
location: {
city: 'London'
}
},
{
firstName: 'Anna',
lastName: 'Andersson',
location: {
city: 'Stockholm'
}
}
];
const obj = applySpec({
The_First_Name: prop('firstName'),
city: path(['location', 'city'])
})
console.log(
map(obj, data)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
<script>const {applySpec, prop, path, map} = R;</script>
这是将
columnDefs
转换为可与applySpec
一起使用的对象的方式:const spec = def => ({[def.label]: apply(def.value, def.args)});
const specs = compose(mergeAll, map(spec));
const columnDefs = [
{
label: 'The_First_Name',
value: prop,
args: ['firstName'] // different number of arguments depending on function
},
{
label: 'City',
value: path,
args: [['location', 'city']]
}
]
const data = [
{
firstName: 'Joe',
lastName: 'Smith',
location: {
city: 'London'
}
},
{
firstName: 'Anna',
lastName: 'Andersson',
location: {
city: 'Stockholm'
}
}
]
const spec = def => ({[def.label]: apply(def.value, def.args)});
const specs = compose(mergeAll, map(spec));
console.log(
map(applySpec(specs(columnDefs)), data)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
<script>const {apply, compose, mergeAll, map, prop, path, applySpec} = R;</script>
关于javascript - 管道,带有动态参数的ramda,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56186381/