Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement