2015-09-05 76 views
2

我剛剛開始使用immutable.js,並且在解決如何在數組中的對象上設置新屬性時遇到問題。我無法在這種變化的文檔中找到任何示例。immutable.js映射到數組(List)並添加一個屬性

我基本上只是試圖採取改變這種:

[{ 
    gitInfo: {id: 8001, host: '', …}, 
    module: {id: 24875, name: "blah", …} 
}...] 

這樣:

[{ 
    gitInfo: {id: 8001, host: '', …}, 
    module: {id: 24875, name: "blah", isStared: true …} 
}...] 

所以瓦特/ immutable.js我會是這樣的:

function markModules(modules) { 
    modules.map((module) => { 
     module.module.isStarred = false; 
     if (contains(this.props.stars, module.module.id)) { 
     module.module.isStarred = true; 
     } 
    }) 
    return modules; 
    } 

我假設我需要像set() with a List這樣的東西,但是再次,我沒有找到任何示例如何做到這一點。

感謝您提供示例的任何提示或鏈接。

回答

3

你會這樣做你會沒有Immutable.js(.map)。

const data = Immutable.fromJS([{ 
    gitInfo: {id: 8001, host: ''}, 
    module: {id: 24875, name: "blah"} 
}, { 
    gitInfo: {id: 6996, host: ''}, 
    module: {id: 666, name: "wef"} 
}]); 

const transformed = data.map((x) => { 
    return x.get('module').set('isStarred', true); 
}) 

transformed.toJS() === [ 
    { 
    "id": 24875, 
    "name": "blah", 
    "isStarred": true 
    }, 
    { 
    "id": 666, 
    "name": "wef", 
    "isStarred": true 
    } 
] 

如果你想要把額外的邏輯在那裏:

function markModules(modules) { 
    return modules.map((module) => { 
    const isStarred = contains(this.props.stars, module.getIn(['module', 'id'])); 
    return module.setIn(['module', 'isStarred'], isStarred); 
    }) 
} 

的關鍵是把你的if語句到值/函數,而不是返回更新數據結構的值。