Mapping Objects in JavaScript
mapValues is a way to manipulate Objects by iterating through thier values like you would do with map on Arrays. For an example where this is useful, there is an Object to track where columns in a grid are inserted. The keys are the column names and the values are the positions from 0. Later a new grid is made with a new column so all other ids must be shifted:
const grid1Columns = { name: 0, location: 1, url: 2, }; // Later another grid is added that is based on the current one let grid2Columns = {...grid1Columns}; grid2Columns.id = -1; grid2Columns = mapValues(grid2Columns, (index) => index + 1); console.log(grid1Columns); // { name: 0, location: 1, url: 2 } console.log(grid2Columns); // { name: 1, location: 2, url: 3, id: 0 }
mapKeys just does the same, but with keys:
grid2Columns = mapKeys(grid2Columns, (name) => name + 'Column'); console.log(grid2Columns); // { nameColumn: 1, locationColumn: 2, urlColumn: 3, idColumn: 0 }
Finally, a mapObject can be used to do everything at once instead:
const grid2ColumnsB = mapObject({ id: -1, ...grid1Columns}, (index, name) => { return { key: name + 'Column', value: index + 1 }; }); console.log(grid2ColumnsB); // { idColumn: 0, nameColumn: 1, locationColumn: 2, urlColumn: 3 }
Many utility libraries like Lodash support mapValues and mapKeys. Though there seems to be no general mapObject. Probably, because it is rare that both operations would want to be done in real world situations.
Here are the implementations of each function without libraries:
function mapValues(obj, callback) { // Make sure the original object is not modified const newObj = {}; for (let key in obj) { newObj[key] = callback(obj[key]); } return newObj; } function mapKeys(obj, callback) { // Make sure the original object is not modified const newObj = {}; for (let key in obj) { const newKey = callback(key); newObj[newKey] = obj[key]; } return newObj; } function mapObject(obj, callback) { // Make sure the original object is not modified const newObj = {}; for (let keyInObj in obj) { const {key, value} = callback(obj[keyInObj], keyInObj); newObj[key] = value; } return newObj; }
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/mapObject.js












