2017-04-27 90 views
0

我有两个列表,我试图将它们组合到一个新列表中,以便现有的id被更新,新的列表被添加到列表中,然后按id排序。有没有更好或更有效的方法来做到这一点?组合两个不可变列表的最佳方式是什么?

// Original list 
const list = Immutable.List([ 
    { id: 1, name: 'List Item 1' }, 
    { id: 2, name: 'List Item 2' }, 
    { id: 3, name: 'List Item 3' }, 
]); 

// One updated item and two new items 
const newList = Immutable.List([ 
    { id: 2, name: 'Updated List Item 2' }, 
    { id: 4, name: 'New List Item 4' }, 
    { id: 5, name: 'New List Item 5' }, 
]); 

// Get updated ids 
const ids = newList.map((item) => item.id); 

// Filter out updated ids from orignial list 
const filteredList = list.filterNot(item => ids.includes(item.id)); 

// Concat and sort by id 
const concatList = newList 
    .concat(filteredList) 
    .sortBy(item => item.id); 

console.log(concatList.toJS()); 

/* Outputs as desired 
[ 
    { id: 1, name: "List Item 1" }, 
    { id: 2, name: "Updated List Item 2" }, 
    { id: 3, name: "List Item 3" }, 
    { id: 4, name: "New List Item 4" }, 
    { id: 5, name: "New List Item 5" } 
] 
*/ 

回答

2

这是我会怎么做,用reducemerge

function reduceToMap(result, item) { return result.set(item.id, item) } 
 

 
const list = Immutable.List([ 
 
    { id: 1, name: 'List Item 1' }, 
 
    { id: 2, name: 'List Item 2' }, 
 
    { id: 3, name: 'List Item 3' }, 
 
]).reduce(reduceToMap, Immutable.Map()); 
 

 
// One updated item and two new items 
 
const newList = Immutable.List([ 
 
    { id: 2, name: 'Updated List Item 2' }, 
 
    { id: 4, name: 'New List Item 4' }, 
 
    { id: 5, name: 'New List Item 5' }, 
 
]).reduce(reduceToMap, Immutable.Map()); 
 

 

 
console.log(...list.merge(newList).values())
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>

相关问题