Javascript 将对象不可变地添加到作为对象属性的数组并返回新对象的简明方法

Javascript 将对象不可变地添加到作为对象属性的数组并返回新对象的简明方法,javascript,ramda.js,Javascript,Ramda.js,有没有一种更简洁的方法可以在功能上将项添加到作为对象属性的数组中 命令: secitems.sections.push("Test") return secitems 功能性: const R = require("ramada") return Object.assign({}, secitems, { sections: R.append( "Test", secitems.se

有没有一种更简洁的方法可以在功能上将项添加到作为对象属性的数组中

命令:

secitems.sections.push("Test")
return secitems
功能性:

const R = require("ramada")
return Object.assign({}, secitems, {
                sections: R.append(
                    "Test",
                    secitems.sections
                )
            })
与命令式版本相比,我的函数式版本似乎太长、太复杂。有没有更简洁的方法来编写它?

更新(TL;DR)

const R = require('ramda')
return R.mergeWith(R.concat, secitems, { sections: ["Test"] })
我会这样做:

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']}}