DEV Community 👩‍💻👨‍💻

Discussion on: Good Map Usage?

lukeshiru profile image
Luke Shiru

Nah, I would just use objects/arrays to avoid unwanted mutations:

const toDoList = [
    { id: 1, date: "2021-10-12", content: "hello world!" },
    { id: 2, date: "2021-10-13", content: "hope you have a great day!" }

// Reusable function to update or replace by an id property.
const addOrUpdateById = array => item => {
    const index = array.findIndex(({ id }) => id ===;

    return index >= 0
        ? [...array.slice(0, index), item, ...array.slice(index + 1)]
        : [...array, item];

// Because the util is curried, we create a new function from it...
const addOrUpdateToDo = addOrUpdateById(toDoList);

// We should use it to update the state in React
// but as an example, here we map trough it directly
addOrUpdateToDo(usertNote({ date: "2021-10-14", content: "Future me!" })).map(
    ({ id, content }) => <span key={id}>{content}</span>
Enter fullscreen mode Exit fullscreen mode


jmcelreavey profile image
John McElreavey Author

Interesting approach, thanks. I probably would have just updated the existing object rather than creating a new array but your way is better with React. Is there any good examples of a case where you would use a Map object?