Skip to content Skip to sidebar Skip to footer

Convert A Json Object's Keys Into Dot Notation Paths

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

Solution 1:

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

functionpath(a) {
  var list = [];
  (function(o, r) {
    r = r || '';
    if (typeof o != 'object') {
      returntrue;
    }
    for (var c in o) {
      if (arguments.callee(o[c], r + "." + c)) {
        list.push(r.substring(1) + "." + c);
      }
    }
    returnfalse;
  })(a);
  return list;
}
var a = {
  great:{
    grand:{
      parent:{
        child:1
      },
      parent2:1
    }
  }
};
console.log(JSON.stringify(path(a)));

Solution 2:

var path = function (a) {
  var list = [];
  (function(o, r) {
    r = r || '';
    if (_.isArray(o)) {
      returntrue;
    }
    for (var c in o) {
      if (arguments.callee(o[c], r + (r!=""?"[":"") + c + (r!=""?"]":""))) {
        list.push(r + (r!=""?"[":"") + c + (r!=""?"]":""));
      }
    }
    returnfalse;
  })(a);
  return list;
};

With an input of something like this (a deep JSON object of input errors):

{"email":["Enter a valid email."],"billing":{"name":["Enter a billing name."],"line1":["Enter a street address or PO box."],"city":["Enter a city."],"state":["Enter your state abbreviation."],"zip":["Enter a valid 5-digit zip."]},"shipping":{"name":["Enter a billing name."],"line1":["Enter a street address or PO box."],"city":["Enter a city."],"state":["Enter your state abbreviation."],"zip":["Enter a valid 5-digit zip."]},"payment":{"number":["Enter a valid credit card number."],"exp_month":["Enter a valid expiration month."],"exp_year":["Enter a valid expiration year."],"cvc":["Enter a valid CVC."]}}

You get an output like this (names of inputs in array notation in which to attach errors via client-side templates)

["email", "billing[name]", "billing[line1]", "billing[city]", "billing[state]", "billing[zip]", "shipping[name]", "shipping[line1]", "shipping[city]", "shipping[state]", "shipping[zip]", "payment[number]", "payment[exp_month]", "payment[exp_year]", "payment[cvc]"]

Post a Comment for "Convert A Json Object's Keys Into Dot Notation Paths"