更新(TL; DR)
私はこのようにそれを行うだろう:
const seclens = lensProp('sections');
over(seclens, append('Test'), secitems);
//=> {id: 123, sections: ['Foo', 'Bar, 'Test']}
より簡潔にこれを行うには、いくつかの方法があります。この方法の利点は、それがレンズ自体である
const secitems = {id: 123, sections: ['Foo', 'Bar']};
over(lensProp('sections'), 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 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でより多くの情報があります。