Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a JSON object's keys into dot notation paths [duplicate]

Instead of accessing a deep object with a known dot notation, I want to do the opposite: build the dot notation string from the keys of the deep object.

So given the following JSON object:

{
  great:{
    grand:{
      parent:{
        child:1
      },
      parent2:1
    }
  }
}

I'd like to get the following array of paths:

[
  "great.grand.parent.child",
  "great.grand.parent2"
]

Thanks in advance!

like image 502
talentedmrjones Avatar asked Nov 28 '12 04:11

talentedmrjones


1 Answers

Try this. But I don't know why you need this.

function path(a) {
  var list = [];
  (function(o, r) {
    r = r || '';
    if (typeof o != 'object') {
      return true;
    }
    for (var c in o) {
      if (arguments.callee(o[c], r + "." + c)) {
        list.push(r.substring(1) + "." + c);
      }
    }
    return false;
  })(a);
  return list;
}
var a = {
  great:{
    grand:{
      parent:{
        child:1
      },
      parent2:1
    }
  }
};
console.log(JSON.stringify(path(a)));
like image 142
mattn Avatar answered Oct 19 '22 23:10

mattn