问题描述
{
id: "72232915",entryCode: "999",conjunction1: "1234567",conjunction2: "8910111",conjunction3: "1314151",date: "08/02/2017"
}
我想将对象转换为以下格式:
{
id: "72232915",conjunctions: {
1: "1234567"
2: "8910111"
3: "1314151"
},date: "08/02/2017"
}
关于如何实现所需输出的任何想法?
解决方法
这是打字稿的代码(非常特定于您的要求):
let o = {
id: "72232915",entryCode: "999",conjunction1: "1234567",conjunction2: "8910111",conjunction3: "1314151",date: "08/02/2017"
};
const conjunctions = {};
for (const prop in o) {
const regex = /^conjunction(.+)$/;
const matches = prop.match(regex);
if (matches?.length === 2) {
const conjunction = matches[1];
conjunctions[conjunction] = o[prop];
delete o[prop];
}
}
o = Object.assign({},o,{conjunctions});
console.log(o);