本文介绍了将复杂的JavaScript对象转换为点表示法对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,如

{ "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.

注意2:我希望它与我的服务器端控制器动作绑定一起使用。

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

推荐答案

您可以递归添加新对象的属性,然后转换为JSON:

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

这篇关于将复杂的JavaScript对象转换为点表示法对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:17