Tuesday, December 1, 2020

walk a json object, display paths of all parent nodes

One of the interesting things about styled components is that they can handle objects full of CSS stylings, not just strings.

So we have these json objects represented nested stylings, and I wanted to see all the keys (with their full paths) that had children (i.e. ignore any { "color" : "red" } simple properties) 

So a pretty good Comp Sci 101 exercise... 

const json = {
let buffer = '';

function showFullKeysOfParents(json,path){
  const keys = Object.keys(json);
  for(key of keys){
    if(typeof json[key] === 'object'){
      const newpath = `${path}${path===''?'':'.'}${key}`;
      buffer += `${newpath}\n`;

I decided to just punt and use a global variable rather than waste more time fretting about return values and what not. 

The result of that is:


I made a code pen for it. Sidenote: I had to turn off "Match Brackets/Tags". I really don't understand why that kind of auto-complete is the default preference, and why coders like it... the "convenience" of saving a key or two comes no where near outweighing the unpredictability, and if you, say, go back to change the quote situation in a string, you can end up in a nightmare of appearing and disappearing quotes and single quotes.

No comments:

Post a Comment