2016-04-20 38 views
0

我想寫一個函數來更新我有的不可變對象。我正在使用return myitem.updateIn,所以我可以鏈接另一個已經工作的更新ontop。到目前爲止,我有這樣的:控制檯日誌裏更是創下了正確的部分然而,這似乎並不可變,更新裏面的地圖不返回正確的對象

memo.updateIn(['Topics', 'filters'], function(topic) { 
    topic.map(function(singleTopic) { 
    singleTopic.update('filters', function(subTopicFilters) { 
     subTopicFilters.map(function(singleSubTopic) { 
     if(singleSubTopic.get('checked')){ 
      console.log("check", singleTopic.toJS()); 
      return singleTopic.set('checked', true); 
     } 
     }) 
    }) 
    }) 
}); 

,不被更新不可變的映射,因爲我認爲它會。 psycological disorders中的checked值應設置爲true。在這裏看到小提琴,例如https://jsfiddle.net/alexjm/c5edxaue/27/

對於一些上下文中,這是被在幾個單獨.update將在備忘錄爲了像這樣

returnModifiedData(memo) { 
    return memo.update (.... 

    ).update(..... 

    .update(); 

該函數運行返回用於在該過程中的第一步驟中,將其他2已經在工作。我不知道我在做什麼錯誤沒有得到這個更新正確,可能我怎麼試圖.set裏面的單眼?基本邏輯是檢查主題是否包含內部檢查的子主題,如果是,請檢查主題。任何幫助將不勝感激。謝謝!

編輯:忘了補充一下備忘錄本身看起來像:

const memo = { 
    "Topics": { 
    "filters": { 
     "Psychological disorders": { 
     "checked": false, 
     "filters": { 
      "Anxiety disorders": { 
      "filters": {}, 
      "checked": true 
      } 
     } 
     }, 
     "test": { 
     "checked": false, 
     "filters": { 
      "test": { 
      "filters": {}, 
      "checked": false 
      } 
     } 
     } 
    }, 
    "isOpen": false 
    } 
}; 

回答

1

它會更好,如果你能解釋一下什麼是你想達到的邏輯。在Topics->filters

  1. 通過迭代和更新項目:

    我會在這裏想它。

  2. 對於每個singleTopic迭代,進一步遍歷它的filters

  3. 如果任何singleSubTopiccheckedtrue,更新singleTopiccheckedtrue

及以下你可以期待什麼:

const map = { 
 
    "Topics": { 
 
    "filters": { 
 
     "Psychological disorders": { 
 
     "checked": false, 
 
     "filters": { 
 
      "Anxiety disorders": { 
 
      "filters": {}, 
 
      "checked": true 
 
      } 
 
     } 
 
     }, 
 
     "test": { 
 
     "checked": false, 
 
     "filters": { 
 
      "test": { 
 
      "filters": {}, 
 
      "checked": false 
 
      } 
 
     } 
 
     } 
 
    }, 
 
    "isOpen": false 
 
    } 
 
}; 
 

 
let memo = Immutable.fromJS(map); 
 

 
memo = memo.updateIn(['Topics', 'filters'], function(topics) { 
 
    // Remember to return the updated topics. 
 
    return topics.map(function(singleTopic) { 
 
    // If singleTopic has any of its singleSubTopic under filters have value checked=== true 
 
    // update the singleTopic's checked, otherwise return unaltered. 
 
    if (singleTopic.get('filters').some(function(singleSubTopic) { 
 
     return singleSubTopic.get('checked'); 
 
    })) { 
 
     return singleTopic.set('checked', true); 
 
    } 
 
    return singleTopic; 
 
    }); 
 
}); 
 

 
console.log(memo.toJS());
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>

+0

這是非常有幫助,非常感謝你的幫助。 – ajmajmajma

+0

Np,下一次問邏輯,我相信你會更快得到你的答案;) – fuyushimoya