Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flatten an object preserving certain Fields

I would like to flatten this object without flattening the keys $gt and $lt

{
 values:{
  gross_floor_area:{"$gt":200, "$lt":5000},
  nested: {net_floor_area:{"$gt":200, "$lt":5000}}
}}

the desired result would be

{ 'values.gross_floor_area':  { '$gt': 200, '$lt': 5000 },'values.nested.net_floor_area':{"$gt":200, "$lt":5000} }

I have tried using flat library by specifying maxDepth of 2 but only works for gross_floor_area key

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This will return the flattened object, without mutating the original object.

function flatten(obj) {
  const result = {};
  for (const key in obj) {
    if (typeof obj[key] === 'object' && !obj[key].$gt && !obj[key].$lt) {
      const flatObject = flatten(obj[key]);
      for (const x in flatObject) {
        result[`${key}.${x}`] = flatObject[x];
      }
    } else {
      result[key] = obj[key];
    }
  }
  return result;
}

It doesn’t work for all keys starting with $, as you mentioned in the comment to your question, only $gt and $lt. More specifically, it won’t flatten the object that contains these two keys.

FYI, this was pretty much generated by GitHub Copilot. In case you use it, it’s very helpful for achieving this kind of goals.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading