2016-06-21 8 views
2

オブジェクトのプロパティである配列にアイテムを機能的に追加する方法はありますか?オブジェクトのプロパティである配列にオブジェクトを不変に追加して新しいオブジェクトを返す

命令型:

secitems.sections.push("Test") 
return secitems 

機能:

const R = require("ramada") 
return Object.assign({}, secitems, { 
       sections: R.append(
        "Test", 
        secitems.sections 
       ) 
      }) 

私の機能バージョンが不可欠バージョンに比べて長すぎると複雑そうです。それを書くより簡潔な方法がありますか?

答えて

3

更新(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でより多くの情報があります。

2
const R = require('ramda') 
return R.mergeWith(R.concat, secitems, { sections: ["Test"] }) 
関連する問題