如何使用JS解析和交换JavaScript对象?

时间:2017-01-19 06:03:16

标签: javascript jquery json

实际输出:

 {
   "workbookInformation": {
    ...
  },
  "dashboard1": {
    "auto-hidden": "0",
    "maximized": "1",
    "worksheet": {
      "worksheet8": "APAC",
      "worksheet2": "Freq_SC_Value",
      "worksheet3": "L1 Type Filter",
      "worksheet1": "Pillar Name"
    },
    "class": "dashboard",
    "name": "AnalysisByGeography"
  },
  "dashboard2": {
    ...
  },
  "datasources3": {
    ...
  }
}

必填项:

      {
  "workbookInformation": {
    ...
  },
  "AnalysisByGeography": {
    "auto-hidden": "0",
    "maximized": "1",
    "worksheet": {
      "APAC": "worksheet8",
      "Freq_SC_Value": "worksheet2",
      "L1 Type Filter": "worksheet3",
      "Pillar Name": "worksheet1"
    },
    "class": "dashboard",
    "name": "AnalysisByGeography"
  },
  "dashboard2": {
    ...
  },
  "datasources3": {
    ...
  }
}

我尝试使用代码来提供密钥名称。我试过“//jashkenas.github.io/underscore/underscore-min.js”交换密钥。我尝试使用外部JS文件来反转键值对。

2 个答案:

答案 0 :(得分:0)

尝试使用$total。否则,您可能需要拆分给定的数据并将具有相同功能的数组转换为json类型。

答案 1 :(得分:0)

好的,我在这里为你写了怎么做,因为我没有看到更多如何解释它。但我强烈建议,如果你从JavaScript开始,在询问这类问题之前要了解更多。

可能需要其他验证。此外,我只为以“仪表板”开头的键执行此操作,即使我认为它可能适用于所有具有字符串加上数字的键,然后包含一个具有键“名称”的对象。如果你想学习,你应该自己解决这个问题,因为你在这里有一个非常强大的基础。

希望你能像我一样找到学习并且仍然有学习!

var data = 
{
  "workbookInformation": {
    "a": "..."
  },
  "dashboard1": {
    "auto-hidden": "0",
    "maximized": "1",
    "worksheet": {
      "worksheet8": "APAC",
      "worksheet2": "Freq_SC_Value",
      "worksheet3": "L1 Type Filter",
      "worksheet1": "Pillar Name"
    },
    "class": "dashboard",
    "name": "AnalysisByGeography"
  },
  "dashboard2": {
    "a": "..."
  },
  "datasources3": {
    "a": "..."
  }
}

var isDashboard = new RegExp('dashboard[0-9]+', 'i');
var isWorksheet = new RegExp('worksheet[0-9]+', 'i');
for(var dataKey in data) {
	var innerData = data[dataKey];
	if (typeof(innerData["worksheet"]) == "object") {
		var newWS = {};
		for(var wsKey in innerData["worksheet"]) {
			newWS[innerData["worksheet"][wsKey]] = wsKey;
		}
		innerData["worksheet"] = newWS;
	}

	if (isDashboard.test(dataKey) && innerData['name']) {
		delete data[dataKey];
		dataKey = innerData['name'];
	}
	
	data[dataKey] = innerData;
}

console.log(data);