0

I'm trying to create an object from object and list of properties.

 const pick = (obj, ...fields) => {
  return [...fields] = obj
};

How can I realise this?

  • May you share example inputs and outputs of this function? – evolutionxbox Sep 09 '21 at 11:11
  • Another handy and tiny library, SelectQL.js is inspired by Structured Query Language (SQL) for accessing and manipulating Objects in an easy and familiar way. It supports complex Objects and Arrays using Builder Design Pattern. https://www.npmjs.com/package/selectql.js – Nadeem Feb 25 '23 at 18:22

3 Answers3

0

Reduce the list of fields, and take the values from the original object:

const pick = (obj, ...fields) => fields.reduce((acc, field) => ({ ...acc, [field]: obj[field] }), {});

const obj = { a: 1, b: 2, c: 3 };

const result = pick(obj, 'a', 'c');

console.log(result);

You can use the in operator to ignore properties that don't exist on the original object:

const pick = (obj, ...fields) => fields.reduce((acc, field) => {
  const value = obj[field];
  
  if(field in obj) acc[field] = value;

  return acc;
}, {});

const obj = { a: 1, b: 2, c: 3 };

const result = pick(obj, 'a', 'c', 'd');

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

Try something like this:

const pick = (obj, ...fields) => Object.fromEntries(Object.entries(obj).filter(([k]) => fields.includes(k)))
Shalom Peles
  • 2,285
  • 8
  • 21
0

Iterate through fields array and check if property is available in obj then put into final object which needs to be returned.

const pick = (obj, ...fields) => {
  const finalObj = { };
  for (field of fields) {
    if (obj[field]) {
      finalObj[field] = obj[field];
    }
  }
  return finalObj;
};

const obj = { name: "test name", age: 25, title: "Mr.", city: "test city" };

console.log(pick(obj, "name", "age", "city", "other"));
Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22