Home > Mobile >  How to generically replace every undefined value within a tree like object structure with the null v
How to generically replace every undefined value within a tree like object structure with the null v

Time:05-03

is there a better way to check of empty data in JSON data ?

Here is the type of JSON I have, sometimes data is missing, which is normal :

{
  "sumRatings": "Private info",
  "phoneNum": "Private info",
  "firstname": "Private info",
  "email": "Private info",
  "fullname": "Private info",
  "talentType": "Private info",
  "ratingCount": "Private info",
  "creationTime": "Private info",
  "lastname": "Private info",
  "currentPosition": "Private info",
  "rgpd": "Private info",
  "bio": "Private info",
  "company": "Private info",
  "whatsapp": "Private info",
  "emptyComs": "Private info",
  "id": "Private info"
}

Here is how I did it :

for (const item of allDocs) {
  var generalData = {
    bio: item.bio == undefined ? null : item.bio,
    fullname: item.fullname == undefined ? null : item.fullname,
    company: item.company == undefined ? null : item.company,
    position: item.position == undefined ? null : item.position,
    profilImg: item.profilImg == undefined ? null : item.profilImg,
    talentType: item.talentType == undefined ? null : item.talentType,
    rating: item.rating == undefined ? null : item.rating,
    contacts: {
      gmeets: item.gmeets == undefined ? null : item.gmeets,
      zoom: item.zoom == undefined ? null : item.zoom,
      phone: item.phone == undefined ? null : item.phone,
    },
    skills: item.skills == undefined ? null : item.skills,
    email: item.email == undefined ? null : item.email,
    firstname: item.firstname == undefined ? null : item.firstname,
    lastname: item.lastname == undefined ? null : item.lastname,
    phone: item.phoneNum == undefined ? null : item.phoneNum,
    ratingCount:
      item.ratingCount == undefined ? null : item.ratingCount,
    sumRatings: item.sumRatings == undefined ? null : item.sumRatings,
    currentPosition:
      item.currentPosition == undefined ? null : item.currentPosition,
    creationTime:
      item.creationTime == undefined ? null : item.creationTime,
    rgpd: item.rgpd == undefined ? null : item.rgpd,
    emptyComs: item.emptyComs == undefined ? null : item.emptyComs,
  };
  console.log(generalData);
}

I wonder if there is a way to avoid puting ... == undefined ? null : ... on every line. Maybe a function that would take the item atributes, check if they are undefined and return "null" if undefined or the actual value if not undefined.

CodePudding user response:

From the above comment ...

"First, if any of the object's properties features an undefined value then this object was never retrieved from valid JSON data since the undefined value is not part of JSON conform encoding. Second, checking all (nested) entries of a tree like structure usually is done by a recursive approach. Third, Object.entries returns all of an objects own enumerable key-value pairs."

function recursivelyNullifyUndefinedValues(obj) {
  Object
    .entries(obj)
    .forEach(([key, value]) => {
      if (!!value && (typeof value === 'object')) {

        recursivelyNullifyUndefinedValues(value);

      } else if (value === undefined) {

        obj[key] = null;
      }
    });
  return obj;
}

const sampleData = {
  talentType: "foo",
  rating: "bar",
  contacts: {
    gmeets: undefined,
    zoom: undefined,
    phone: "baz",
  },
};
console.log('before ...', { sampleData });

console.log('after ...', { returnValue: recursivelyNullifyUndefinedValues(sampleData) });
console.log('after ...', { sampleData });
.as-console-wrapper { min-height: 100%!important; top: 0; }

Edit

Since the OP seems to create a somehow more structured data item from kind of a flat/plain data config there are other techniques/tools like Destructuring assignment / Object destructuring, Destructuring assignment / Default values and Destructuring assignment / Rest syntax

function recursivelyNullifyUndefinedValues(obj) {
  Object
    .entries(obj)
    .forEach(([key, value]) => {
      if (!!value && (typeof value === 'object')) {

        recursivelyNullifyUndefinedValues(value);

      } else if (value === undefined) {

        obj[key] = null;
      }
    });
  return obj;
}

function createNullifiedStructuredDataFromFlatConfig(config) {
  const {
    // handle nullification already
    // via destructuring default values.
    gmeets = null, zoom = null, phone = null, ...rest
  } = config;

  // take care of whatever was left with the `...rest` data.
  return recursivelyNullifyUndefinedValues({
    contacts: {
      gmeets,
      zoom,
      phone,
    },
    ...rest,
  });
}

const flatItemData = {
  talentType: 'foo',
  rating: 'bar',
  gmeets: undefined,
  zoom: undefined,
  phone: 'baz',
  skills: undefined,
  email: 'buzz',
}
const structuredSampleData =
  createNullifiedStructuredDataFromFlatConfig(flatItemData);

console.log({ flatItemData, structuredSampleData });
.as-console-wrapper { min-height: 100%!important; top: 0; }

CodePudding user response:

You could simplify the x == undefined ? null : x parts to x ?? null and wrap it in a function, but you might want to look into a schema validation library like yup.

CodePudding user response:

const typeCheck = (param) => {
 if (typeof param === undefined) {
        return null;
 }
 else {
  return param;
 }
};
for (const item of allDocs) {
var generaldata = {
bio: tpecheck(item.bio),
};
}

CodePudding user response:

You can also shorthand the check simply with boolean or. For example.

...
var generalData = {
    bio: item.bio || null,
    fullname: item.fullname || null,
    company: item.company || null,
    ...

Expression(x || null) evaluates to null if x is undefined or null. Otherwise it evaluates to x.

  • Related