Convert complex JavaScript object to dot notation

2020-02-10 05:30发布

I have an object like

{ "status": "success", "auth": { "code": "23123213", "name": "qwerty asdfgh" } }

I want to convert it to dot notation (one level) version like:

{ "status": "success", "auth.code": "23123213", "auth.name": "qwerty asdfgh" }

Currently I am converting the object by hand using fields but I think there should be a better and more generic way to do this. Is there any?

Note: There are some examples showing the opposite way, but i couldn't find the exact method.

Note 2: I want it for to use with my serverside controller action binding.

4条回答
家丑人穷心不美
2楼-- · 2020-02-10 06:14

I wrote another function with prefix feature. I couldn't run your code but I got the answer. Thanks

https://github.com/vardars/dotize

var dotize = dotize || {};

dotize.convert = function(jsonobj, prefix) {
    var newobj = {};

    function recurse(o, p, isArrayItem) {
        for (var f in o) {
            if (o[f] && typeof o[f] === "object") {
                if (Array.isArray(o[f]))
                    newobj = recurse(o[f], (p ? p + "." : "") + f, true); // array
                else {
                    if (isArrayItem)
                        newobj = recurse(o[f], (p ? p : "") + "[" + f + "]"); // array item object
                    else
                        newobj = recurse(o[f], (p ? p + "." : "") + f); // object
                }
            } else {
                if (isArrayItem)
                    newobj[p + "[" + f + "]"] = o[f]; // array item primitive
                else
                    newobj[p + "." + f] = o[f]; // primitive
            }
        }
        return newobj;
    }

    return recurse(jsonobj, prefix);
};
查看更多
Animai°情兽
3楼-- · 2020-02-10 06:25

You can use the NPM dot-object (Github) for transform to object to dot notation and vice-versa.

查看更多
看我几分像从前
4楼-- · 2020-02-10 06:31

You can recursively add the properties to a new object, and then convert to JSON:

var res = {};
(function recurse(obj, current) {
  for(var key in obj) {
    var value = obj[key];
    var newKey = (current ? current + "." + key : key);  // joined key with dot
    if(value && typeof value === "object") {
      recurse(value, newKey);  // it's a nested object, so do it again
    } else {
      res[newKey] = value;  // it's not an object, so set the property
    }
  }
})(obj);
var result = JSON.stringify(res);  // convert result to JSON
查看更多
老娘就宠你
5楼-- · 2020-02-10 06:32

Here is a fix/hack for when you get undefined for the first prefix. (I did)

var dotize = dotize || {};

dotize.parse = function(jsonobj, prefix) {
  var newobj = {};
  function recurse(o, p) {
    for (var f in o)
    {
      var pre = (p === undefined ? '' : p + ".");
      if (o[f] && typeof o[f] === "object"){
        newobj = recurse(o[f], pre + f);
      } else {
        newobj[pre + f] = o[f];
      }
    }
    return newobj;
  }
  return recurse(jsonobj, prefix);
};
查看更多
登录 后发表回答