DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

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

/**
 * 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

Top comments (3)

Collapse
 
ashishk1331 profile image
Ashish Khare😎

So this was a clickbait!

Collapse
 
ml318097 profile image
Mehul Lakhanpal

Hmm... Depends on your perspective 🤘

Collapse
 
ashishk1331 profile image
Ashish Khare😎

😊