2016-05-12 32 views
1

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

即,

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]}) 
+0

'mergeWith'按预期工作。您的愿望是非常规的,并且可能通过手动将“朋友”更改为“obj2.friends”来实现。 – hazardous

+0

我知道这是默认行为,但我需要我描述的功能 – DrivingInsanee

+0

在这种情况下,只需使用set更新合并对象中的好友列表并使用首选列表。 – hazardous

回答

2

不可改变给你一个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]})