组合两个不可变列表的最佳方法是什么?

时间:2017-04-27 12:02:29

标签: merge ecmascript-6 concat reduce immutable.js

我有两个列表,我试图将它们组合到一个新列表中,以便更新现有的ID,并将新的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" }
]
*/

1 个答案:

答案 0 :(得分: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>