Home > Enterprise >  Javascript - Get object fields using a given array of keys
Javascript - Get object fields using a given array of keys

Time:09-29

Given this object:

const userData = {
  avatar: undefined,
  name: "Raul",
  username: "raulito",
  celebrity: true
}

I need to implement a method that receives a list of keys (i.e., ["avatar", "name", "username"]) and get the corresponding values of the userData object, ignoring undefined values.

How can I do this using modern javascript syntax?

function denormalizeUserData(userData, ...fields) {
  const denormalized = {};

  // For each key (field), get its value from userData, ignoring if undefined
  
  return denormalized;
}

So, if I do:

 denormalizeUserData(userData, "avatar", "name");

The method must return me:

{
  name: "Raul,
}

Ignoring avatar, as it is undefined.

This is my attempt. I need modern syntax.

const userData = {
  avatar: undefined,
  name: "Raul",
  username: "raulito",
  celebrity: true
}

function denormalizeUserData(userData, ...fields) {
  const denormalized = {};

  fields.forEach((key) => {
    const value = userData[key];

    if(typeof value !== "undefined") {
      denormalized[key] = value;
    } 
  })

  return denormalized;
}

console.log(denormalizeUserData(userData, "celebrity", "name", "avatar"))

CodePudding user response:

function denormalizeUserData(userData, ...fields) {
  const denormalized = {};

  for (const field of fields) {
    if (userData[field] !== undefined) denormalized[field] = userData[field];
  }
  
  return denormalized;
}

Edit: in case someone says a code-only answer is blah blah blah

This is simple enough to be a simple code block.

CodePudding user response:

You can get the object property/value pairs with Object.entries, then use Array.filter to filter out the pairs whose property name is not included in fields and whose value is undefined, then use Object.fromEntries to convert it back to an object.

const userData = {
  avatar: undefined,
  name: "Raul",
  username: "raulito",
  celebrity: true
}

function denormalizeUserData(userData, ...fields) {
  return Object.fromEntries(Object.entries(userData).filter(e => fields.includes(e[0]) && e[1] != undefined))
}

console.log(denormalizeUserData(userData, "avatar", "name"))

CodePudding user response:

Grab the Object.entries and build a new object if there is a value, and if the args array includes the key.

const userData = {
  avatar: undefined,
  name: "Raul",
  username: "raulito",
  celebrity: true
};

function denormalizeUserData(obj, ...args) {
  const out = {};
  for (let [key, value] of Object.entries(obj)) {
    if (value && args.includes(key)) {
      out[key] = value;
    };
  }
  return out;
}

console.log(denormalizeUserData(userData));
console.log(denormalizeUserData(userData, 'avatar', 'name'));
console.log(denormalizeUserData(userData, 'avatar', 'name', 'celebrity'));

  • Related