DEV Community

loading...

A single function to add, update, read & delete from an array

318097 profile image Mehul Lakhanpal Originally published at codedrops.tech ・1 min read
/**
 * Perform CRUD on arrays of objects
 * @param {array} arr - Input array
 * @param {string} cmd - Operation to perform
 * @param {string} payload - Element with the data
 */
const crux = (arr = [], cmd, payload) => {
  if (!arr) return [];
  if (!payload) return arr;

  switch (cmd) {
    case "add":
      return [...arr, payload];
    case "update":
      return arr.map((item) =>
        item.id === payload.id ? { ...item, ...payload } : item
      );
    case "read":
      return arr.find((item) => item.id === payload.id);
    case "delete":
      return arr.filter((item) => item.id !== payload.id) || [];
  }
};

const data = [{ name: "AB", id: 1 }];

crux(data, "add", { name: "CD", id: 2 }); // [ { name: 'AB', id: 1 }, { name: 'CD', id: 2 } ]

crux(data, "update", { name: "Updated AB", id: 1 }); // [ { name: 'Updated AB', id: 1 } ]

crux(data, "read", { id: 1 }); // { name: 'AB', id: 1 }

crux(data, "delete", { id: 1 }); // []
Enter fullscreen mode Exit fullscreen mode

Thanks for reading 💙

Follow @codedrops.tech for daily posts.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech

Discussion (3)

pic
Editor guide
Collapse
hugekontrast profile image
Ashish Khare😎

So this was a clickbait!

Collapse
318097 profile image
Mehul Lakhanpal Author

Hmm... Depends on your perspective 🤘

Collapse
hugekontrast profile image