应用背景
在前两天,项目中使用tree时遇到要把后端传到前端的转换为自己需要的key。取到的是JSON数组,但是key不是我想要的key,需要通过js来转换成自己需要的key的形式。收到的格式类似这样:
var data = [{
"groupId": "01",
"name": "第一组"
}, {
"groupId": "02",
"name": "第二组",
"childGroups": [{
"groupId": "0201",
"name": "2.1组",
"childGroups": [{
"groupId": "020101",
"name": "2.1.1组"
}, {
"groupId": "020102",
"name": "2.1.2组"
},]
}, {
"groupId": "0202",
"name": "2.2组"
}]
}];
js方法
在线示例.
/*
* 调用方式:
* jsonArrayFormat(data, ['groupId', 'name'], ['id', 'name'], ['childGroups', 'children'])
* 参数1:json数组 data
* 参数2:旧key ['groupId', 'name']
* 参数3:新key ['id', 'name']
* 参数4:旧新子节点 [oldChildrenListKey, newChildrenListKey]
*/
function jsonArrayFormat(arr, oKeys, nKeys, childKeys) {
if (oKeys.length !== nKeys.length) {
return new Throw('新旧参数个数不匹配');
}
var newArray = [];
arr.forEach(function (i, index) {
var obj = {};
for (var x = 0; x < oKeys.length; x++) {
obj[nKeys[x]] = i[oKeys[x]];
}
newArray.push(obj);
if (i[childKeys[0]] != null && i[childKeys[0]].length > 0) {
newArray[index][childKeys[1]] = jsonArrayFormat(i[childKeys[0]], oKeys, nKeys, childKeys);
}
});
return newArray;
}