/**
* 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 }); // []
Thanks for reading 💙
Follow @codedrops.tech for daily posts.
Instagram ● Twitter ● Facebook
Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript
codedrops.tech
Top comments (3)
So this was a clickbait!
Hmm... Depends on your perspective 🤘
😊