2016-05-12 93 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]})