[Javascript] Creating an Immutable Object Graph with Immutable.js Map()

时间:2022-02-09 19:13:23

Learn how to create an Immutable.Map() through plain Javascript object construction and also via array tuples.

console.clear();
// Can be an object
var map = Immutable.Map({key: "value"});
console.log(map.get("key")); //"value" // Can be an array
var map = Immutable.Map([["key", {"name": "Zhentian"}]]);
console.log(map.get("key").name); //"Zhentian" // size prop
console.log(map.size); //
mocha.setup('bdd');
const expect = chai.expect; function createObjTodos(numTodos) { var obj = {}
_.each(_.range(numTodos), (index) => {
const todoSequence = String(index+1);
obj['todo'+todoSequence] = {
title: 'Todo '+todoSequence,
value: `Make ${todoSequence} happen`
};
}); return obj; } describe('Creating an Immutable Object Graph with Immutable.js Map()', () => { it('should create Map() with matching keys', () => { const data = {
"todo1": {
title: "Todo 1",
value: "Make it happen"
},
"todo2": {
title: "Todo 2",
value: "Make it happen"
}
} let map = Immutable.Map(data);
expect(map.get("todo1").title).to.equal("Todo 1"); }); it('should create Map() with keys from array tuples', () => { let map = Immutable.Map([["todo1", {title: "Todo 1"}]]) // Note the array within array
expect(map.get("todo1").title).to.equal("Todo 1"); }); it('should create Map() with matching size to number of keys', () => { let map = Immutable.Map(createObjTodos(3))
expect(map.size).to.equal(3); }); }); mocha.run();