Home > Net >  Creates an object composed of the picked object properties: [duplicate]
Creates an object composed of the picked object properties: [duplicate]

Time:09-17

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?

CodePudding user response:

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

CodePudding user response:

Try something like this:

const pick = (obj, ...fields) => Object.fromEntries(Object.entries(obj).filter(([k]) => fields.includes(k)))

CodePudding user response:

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

  • Related