【Web前端问题】js如何高效更改对象中属性名
如图中的一个json
对象:
[ {
"Id":"3972679ef2c04151972b376dd88e6413",
"T_CourseId":"7a4494aae1804d3e94094583249750fe",
"CourseName":"英语",
"Code":"english"
},
{
"Id":"5665d803e7994b26a56c6287d12c2090",
"T_CourseId":"75761ad2ce23498c9f9db134ab844aec",
"CourseName":"药物化学",
"Code":"ywhx"
}
]
怎么使用js
高效的将其中的CourseName
更改为title
,得到结果如下:
[ {
"Id":"3972679ef2c04151972b376dd88e6413",
"T_CourseId":"7a4494aae1804d3e94094583249750fe",
"title":"英语",
"Code":"english"
},
{
"Id":"5665d803e7994b26a56c6287d12c2090",
"T_CourseId":"75761ad2ce23498c9f9db134ab844aec",
"title":"药物化学",
"Code":"ywhx"
}
]
回答:
var aaa = [ {
"Id":"3972679ef2c04151972b376dd88e6413",
"T_CourseId":"7a4494aae1804d3e94094583249750fe",
"CourseName":"英语",
"Code":"english"
},
{
"Id":"5665d803e7994b26a56c6287d12c2090",
"T_CourseId":"75761ad2ce23498c9f9db134ab844aec",
"CourseName":"药物化学",
"Code":"ywhx"
}
]
var bbb= JSON.parse(JSON.stringify(aaa).replace(/CourseName/g,"title"));
console.log(bbb)
回答:
arr = JSON.parse(jsonObj);arr.map(item => {
item.title = item.CourseName;
delete item.CourseName;
return item;
})
回答:
var arr = [ {
"Id":"3972679ef2c04151972b376dd88e6413",
"T_CourseId":"7a4494aae1804d3e94094583249750fe",
"CourseName":"英语",
"Code":"english"
},
{
"Id":"5665d803e7994b26a56c6287d12c2090",
"T_CourseId":"75761ad2ce23498c9f9db134ab844aec",
"CourseName":"药物化学",
"Code":"ywhx"
}
];
arr.forEach(function(item){
item.title = item.CourseName;
delete item.CourseName;
})
或者对每一项用JSON.stringify()转换成字符串,用replace替换,再用JSON.parse()转回来
回答:
如果只是json的话。。那就简单多了
replace一下就行了。
回答:
目前觉得还是 转换字符串然后replace,如果是遇到多重对象嵌套也可以用
回答:
用foreach的方式,不要用replace的方式,万一你的属性里面包含了该字符串就被替换掉了,当然这个可能性很小。
回答:
var aaa = [ {
"Id":"3972679ef2c04151972b376dd88e6413",
"T_CourseId":"7a4494aae1804d3e94094583249750fe",
"CourseName":"英语",
"Code":"english"
},
{
"Id":"5665d803e7994b26a56c6287d12c2090",
"T_CourseId":"75761ad2ce23498c9f9db134ab844aec",
"CourseName":"药物化学",
"Code":"ywhx"
}
]
var copyTrans = function(obj, typeArr) {
let result;
let toString = Object.prototype.toString;
if(toString.call(obj) === '[object Array]'){
result = [];
for(let i = 0; i < obj.length; i++){
result[i] = copyTrans(obj[i], arguments[1])
}
}else if(toString.call(obj) === '[object Object]'){
result = {};
for (let _key in obj) {
if (obj.hasOwnProperty(_key)) {
let flag = 0, _value = null;
for (let j = 0; j < arguments[1].length; j ++) {
if (arguments[1][j].key === _key) {
flag = 1;
_value = arguments[1][j].value
}
}
if (flag)
result[_value] = copyTrans(obj[_key], arguments[1])
else
result[_key] = copyTrans(obj[_key], arguments[1])
}
}
}else{
return obj
}
return result
};
console.log(copyTrans(aaa, [{ key: "CourseName", value: "title" }]));
以上是 【Web前端问题】js如何高效更改对象中属性名 的全部内容, 来源链接: utcz.com/a/143565.html