Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

syntax - Convert complex JavaScript object to dot notation object

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...