-1

Trying to see if there is a shorthand/trick way of creating a flatten map from a nested object. The nested properties to be separated by '.' when drilling down

i.e.

const settings = { 
          "canFly": "false",
            "school": {
                "highschool": true,
                "college": true
        }
};

Map to be something like:

{ 
  "canFly": false, 
  "school.highschool" : true, 
  "school.college" : true, 
}

I currently have some logic which will spit out what I need but would like to know if there is trick to doing this. (Want to use something that is available other than redoing something)

Miguel
  • 1,157
  • 1
  • 15
  • 28
  • 1
    @AlexandervanOostenrijk there's probably faster ways since 2013 :p but I guess the OP didn't ask for fast – Bravo Mar 03 '22 at 07:22
  • 2
    what do you mean by "shorthand" ... like a simple function that you can call with the object you want to flatten? no, you'll have to write some code that's at least a few lines long - P.S. you want to flatten an object - you have no JSON in your question, flatten is javascript object – Bravo Mar 03 '22 at 07:23
  • Yes, kinda. I wanted to see if there was a different way instead of coding it out. This is similar to what I am doing atm but want to see if there was some fancy tricks to do this. – Miguel Mar 03 '22 at 07:26
  • Thanks @Bravo! I'll update my question =] – Miguel Mar 03 '22 at 07:28

1 Answers1

0

you can :

  • use a recursive function for this
  • use Object.entries or Object.keys to iterate on each elem
  • check if property value is an object and recall the function

const settings = { 
  "canFly": "false",
    "school": {
        "highschool": true,
        "college": true
  }
};

let flatObj = {};

function flat(toFlat, flatObj, parent) {
  Object.entries(toFlat).forEach(elem => {
    if (typeof elem[1] === 'object') {
     flat(elem[1], flatObj, elem[0] + '.');
    } else {
      flatObj[parent+elem[0]] = elem[1];
    }
  });
}

flat(settings,flatObj, '')
console.log(flatObj);
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35