immutablejs mergeWith对象但覆盖新列表

时间:2016-05-12 16:29:44

标签: immutable.js

我正在将对象合并在一起,但我遇到的一个问题是,当我将一个对象与一个列表合并,而不是使用另一个对象时,它将它们组合在一起。无论如何要解决这个问题吗?

obj1 = fromJS({name: 'kim', friends: [1,2,3]})
obj2 = fromJS({pet: 'Alex', friends: [4,5,6]})
obj1.mergeWith(obj2)
===> Desired Result
obj3 = fromJS({name: 'kim', pet: 'Alex', friends: [4,5,6]})
===> Actual Result
obj3 = fromJS({name: 'kim', pet: 'Alex', friends: [1,2,3,4,5,6]})

1 个答案:

答案 0 :(得分:3)

immutable为您提供了一个mergeWith函数,可以让您定义如何处理冲突。

export function mergeWithoutList(prev, next){
    if(typeof next == 'object'){
        if(List.isList(prev)){
            return next
        }else{
            return prev.mergeWith(mergeWithoutList, next)
        }
    }
    return next
}

    obj3 = obj1.mergeWith(mergeWithoutList, obj2)
=>
obj3 == fromJS({name: 'kim', pet: 'Alex', friends: [4,5,6]})