jsオブジェクトの属性は、ラクダのピークの名前(数字付き)を下線に変えて命名されます.
2251 ワード
infoに似たフォーマットをinfo 2に変換します.
var info = {
id: 1,
id1: 2,
userName1: ' ',
userName2: ' ',
userName3: ' ',
userAge: 45,
userAge1: 46,
userAge2: 47
}
var info2 = {
id: 1,
id_1: 2,
user_name_1: ' ',
user_name_2: ' ',
user_name_3: ' ',
user_age: 45,
user_age_1: 46,
user_age_2: 47
}
部下の2つの解決策:かなりスマートな答えと言えます.1行で解決します.// segmentDefault asseek :
const toLine = hump => hump.replace(/([A-Z]|\d)/g, (a, l) => `_${l.toLowerCase()}`);
var info = {
id: 1,
id1: 2,
userName1: ' ',
userName2: ' ',
userName3: ' ',
userAge: 45,
userAge1: 46,
userAge2: 47
};
var newObj = {}
for (let k in info) {
newObj[toLine(k)] = info[k]
}
console.log(newObj)
私の答えは長い間考えました. 答えは空を飛ぶと言ってもいいです.私の答えは地上を登ることです.
var info = {
id: 1,
id1: 2,
userName1: ' ',
userName2: ' ',
userName3: ' ',
userAge: 45,
userAge1: 46,
userAge2: 47
}
var info2 = {
id: 1,
id_1: 2,
user_name_1: ' ',
user_name_2: ' ',
user_name_3: ' ',
user_age: 45,
user_age_1: 46,
user_age_2: 47
}
function copy(obj){//
var newobj = {};
for ( var attr in obj) {
newobj[attr] = obj[attr];
}
return newobj;
}
var changeObj = function (obj) {
var copyobj = copy(obj)
var regNum = new RegExp(/\d/)
var regStr = new RegExp(/[A-Z]/g)
var arr = Object.keys(obj);
var newObj = {}
arr.forEach((k, index) => {
var kArr = k.split('')
var newK = ''
kArr.forEach((item,index)=>{
if(regNum.test(item)){
kArr[index] = "_" + item
}
if(regStr.test(item)){
kArr[index] = "_" + item.toLowerCase()
}
})
newKey = kArr.join('')
newObj[newKey] = obj[k]
console.log(newKey)
})
console.log(newObj)
return newObj
}
changeObj(info)