DEV Community

loading...

Implement custom '.pick()' for objects

Mehul Lakhanpal
Full stack Developer | Micro-blogging on Web Development at codedrops.tech | Creator of File Ops, Note Box, GitHub Marker
Originally published at codedrops.tech ・1 min read
const pick = (obj = {}, keys = []) => {
  const result = {};

  for (const key in obj) {
    if (keys.includes(key)) {
      result[key] = obj[key];
    }
  }
  return result;
};

const obj = {
  name: "Mehul",
  age: 27,
  email: "codedrops.tech@gmail.com",
  website: "codedrops.tech",
};

const keysToInclude = ["name", "age"];

console.log(pick(obj, keysToInclude)); // { name: 'Mehul', age: 27 }
Enter fullscreen mode Exit fullscreen mode

Thanks for reading 💙

Follow @codedrops.tech for more.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack

codedrops.tech


Projects

File Ops - A VS Code extension to easily tag/alias files & quick switch between files

Discussion (0)