Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
Creates an object composed of the picked object properties:

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

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);

about 4 years ago · Juan Pablo Isaza Report

0

Try something like this:

const pick = (obj, ...fields) => Object.fromEntries(Object.entries(obj).filter(([k]) => fields.includes(k)))
about 4 years ago · Juan Pablo Isaza Report

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"));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!