工作中,写了个有意思的函数: self.upper.dataSourceTypes = JSON.parse(msg); //加载 库类型 //数据属性转换 var dataTypes = changeJsonName({changeName:{"TypeName":"name","TypeID":"id"},objs:self.upper.dataSourceTypes}); 把对象中的"TypeName","TypeID" 改成 name","id" //欢迎有兴趣的朋友指正优化!!! /* *JSON 属性名转换 *参数形式:{changeName:{a:A,b:B},objs:obj} => 例子: {changeName:{"id":"KEY"},objs:[{id:2},{id:4}]} id为2的JSON对象(数组)改变成[{KEY:2,KEY:4}] *changeName要修改的对象属性名=>{a:A,b:B},objs该对象/对象数组 */ function changeJsonName(o){ var newObj = []; if(o.hasOwnProperty(“changeName”)){ if(o.hasOwnProperty(“objs”)){ var cloneStr = JSON.stringify(o.objs); var cloneObj = JSON.parse(cloneStr); var doit = function(obj){
if(obj.constructor == Array){
for(var i=0;i<obj.length;i++){
doit(obj[i]);
}
}else{
//循环该对象的属性
for(var i in obj){
//循环要改变的属性名
for(var x in o.changeName){
//如果名称相同
if(x == i){
obj[o.changeName[x]] = obj[i];
delete obj[i];
}
}
}
}
}
doit(cloneObj);
return cloneObj;
}
}
return false;
}
//欢迎有兴趣的朋友指正优化!!!
7 回复
var _ = require('lodash');
function changeKeyNames(obj, namesMap) {
return _.transform(obj, function(result, value, key) {
result[namesMap[key] || key] = value;
});
}
changeKeyNames({'a': 1, 'b': 2, 'c': 3}, {'a': 'A', 'b': 'B'});
// → {'A': 1, 'B': 2, 'c': 3}