自己写了半天还是无法实现,最多只能替换一层的key,多层太难了
let result = {};
Object.keys(property).forEach(key => {
let value = property[key];
if ({}.toString.call(value) === '[object Object]') {
value = Object.keys(property[key])[0];
}
if (data.hasOwnProperty(value)) {
result[key] = data[value];
}
})
需要替换的规则
const property = {
userId: 'user_id',
userName: 'user_name',
product: {
'order_attrs': {
attrId: 'id',
attrName: 'attr_name',
attrValue: 'attr_value'
}
},
userAddress: {
'address': {
region: 'region',
avatar: 'image_url',
phoneNumber: {
'phone': {
one: 'a',
two: 'b'
}
}
}
}
}
需要替换的数据
const data = {
user_id: '652',
user_name: '思否',
order_attrs: [{
id: 345,
attr_name: '型号',
attr_value: 'iphone'
},
{
id: 1897,
attr_name: '容量',
attr_value: '256G'
}
],
address: {
region: '北京市',
image_url: '/xxx/aaa.jpg',
phone: {
a: 'eeee',
b: 'ccc'
}
}
}
替换的结果
const result = {
userId: '652',
userName: '思否',
product: [{
attrId: 345,
attrName: '型号',
attrValue: 'iphone'
},
{
attrId: 1897,
attrName: '容量',
attrValue: '256G'
}
],
userAddress: {
region: '北京市',
imageUrl: '/xxx/aaa.jpg',
phoneNumber: {
one: 'eeee',
two: 'ccc'
}
}
}
###规则有点复杂 最好是优化设计。
###如果无法重新设计,可以尝试广度优先遍历,一层层替换
###function replaceObj(sourceObj, rule) {
function getEntries(obj) {
return Object.entries(obj).map(item => {
const isObj = Object.prototype.toString.call(item[1]) === '[object Object]'
const obj = {}
obj[item[0]] = isObj ? Object.keys(item[1])[0] : item[1]
return isObj ? [obj, getEntries(item[1])] : obj
}).flat(Infinity)
}
let result = JSON.stringify(sourceObj)
getEntries(rule).forEach(item => {
const reg = new RegExp(`"${Object.values(item)[0]}"`, 'g')
result = result.replace(reg, `"${Object.keys(item)[0]}"`)
})
return JSON.parse(result)
}