是否有更简洁的方法将项目功能性地添加到作为对象属性的数组中?
势在必行:
const R = require("ramada")
return Object.assign({}, secitems, {
sections: R.append(
"Test",
secitems.sections
)
})
功能:
html{
background: #fff url('//www.xxxxxxxxx.xxx/gray.jpg') center top no-repeat;
background-attachment: initial;
background-size: contain;
background-position-y: 0;
}
与命令式版本相比,我的功能版本似乎太长而且复杂。是否有更简洁的方式来编写它?
答案 0 :(得分:3)
更新(TL; DR)
我会这样做:
const seclens = lensProp('sections');
over(seclens, append('Test'), secitems);
//=> {id: 123, sections: ['Foo', 'Bar, 'Test']}
有许多方法可以更简洁地完成此操作。其中一些还解决了原始代码无法处理的问题:
// This works fine
const secitems = {id: 123, sections: ['Foo', 'Bar']};
secitems.sections.push("Test")
secitems; //=> {id: 123, sections: ['Foo', 'Bar', 'Test']}
// But this is a problem
const secitems = {id: 123};
secitems.sections.push("Test")
secitems; //=> throws "secitems.sections is undefined"
我使用Ramda的首选方法是使用镜片:
const secitems = {id: 123, sections: ['Foo', 'Bar']};
over(lensProp('sections'), append('Test'), secitems);
//=> {id: 123, sections: ['Foo', 'Bar, 'Test']}
这样做的好处是镜头本身在几种情况下都很有用:
const seclens = lensProp('sections');
const getSections = view(seclens);
getSections(secitems); //=> ['Foo', 'Bar']
const setSections = set(seclens);
setSections(['Baz, Qux'], secitems)
//=> {id: 123, sections: ['Baz', 'Qux']}
setSections(['Baz', 'Qux'], {id: 456})
//=> {id: 456, sections: ['Baz', 'Qux']}
如果您的数据结构发生变化,唯一需要更改的代码就是镜头定义本身:
const obj = {id: 123, secitems: {sections: ['Foo', 'Bar']}};
over(lensPath(['secitems', 'sections']), append('Test'), obj);
//=> {id: 123, secitems: {sections: ['Foo', 'Bar, 'Test']}}
或者
const seclens = lensPath(['secitems', 'sections']);
const getSections = view(seclens);
getSections(obj); //=> ['Foo', 'Bar']
const setSections = set(seclens);
setSections(['Baz, Qux'], obj)
//=> {id: 123, secitems: {sections: ['Baz', 'Qux']}}
setSections(['Baz', 'Qux'], {id: 456})
//=> {id: 456, secitems: {sections: ['Baz', 'Qux']}}
Ramda's lens
documentation中有更多信息。
答案 1 :(得分:2)
const R = require('ramda')
return R.mergeWith(R.concat, secitems, { sections: ["Test"] })