Creating new keys

Let's revisit the earlier example where we mapped a list of names. We'll do the same thing here, except that we'll add the resulting string to each map as a new key-value pair:

const capitalize = s =>
`${s.charAt(0).toUpperCase()}${s.slice(1)}`;
const myList = List.of(
Map.of('first', 'joe', 'last', 'brown', 'age', 45),
Map.of('first', 'john', 'last', 'smith', 'age', 32),
Map.of('first', 'mary', 'last', 'wise', 'age', 56)
);
const myMappedList = myList.map(
v => v.set('name', [
capitalize(v.get('first')),
capitalize(v.get('last'))
].join(' '))
);

console.log('myList', myList.toJS());
// -> myList [ { first: 'joe', last: 'brown', age: 45 },
// -> { first: 'john', last: 'smith', age: 32 },
// -> { first: 'mary', last: 'wise', age: 56 } ]

console.log('myMappedList', myMappedList.toJS());
// -> myMappedList [ { first: 'joe', last: 'brown', age: 45, name: 'Joe Brown' },
// -> { first: 'john', last: 'smith', age: 32, name: 'John Smith' },
// -> { first: 'mary', last: 'wise', age: 56, name: 'Mary Wise' } ]

Instead of returning the resulting string from our map() iteratee, we're returning a new map instance by calling set(). The new list of maps each have a name key now.

This type of mapping is useful if you already have code that processes lists of maps and it expects a name key. You can easily add the key rather than change the list processing code.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.68.14