2017-05-28 35 views
1

內如果我有一個不變的列表,如:如何更新地圖列表

List([ 
    Map({ something: 1 }), 
    Map({ something: 2 }), 
]) 

我怎會設置的東西= 5,其中一些= 1?

回答

1

您可以使用map + set爲了實現這一

console.clear(); 
 

 
const list = Immutable.List([ 
 
    Immutable.Map({ something: 1 }), 
 
    Immutable.Map({ something: 2 }), 
 
    Immutable.Map({ something: 4 }), 
 
    Immutable.Map({ something: 1 }) 
 
]) 
 

 

 
const newList = list.map(item => 
 
    item.get("something") === 1 ? item.set("something", 5) : item 
 
); 
 

 
console.log('Old',JSON.stringify(list.toArray(),null, "")); 
 
console.log('New',JSON.stringify(newList.toArray(),null, ""));
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.2/immutable.min.js"></script>

0

@ QOP的回答會是不錯的,如果你正在尋找一個特定的鍵。

如果要更新每個地圖中的多個值,可以在list.map調用中使用.mapEntries()

things 
    .map(thing => { 
     return thing.mapEntries(([ k, v ]) => { 
     const val = (v === 5) ? 1 : v; 
     return [ k, val ] 
     }) 
    }); 

here is a link to working plunk