87,987
社区成员
发帖
与我相关
我的任务
分享
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: 'csdn',
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: 'csdn',
product: [{
attrId: 345,
attrName: '型号',
attrValue: 'iphone'
},
{
attrId: 1897,
attrName: '容量',
attrValue: '256G'
}
],
userAddress: {
region: '北京市',
imageUrl: '/xxx/aaa.jpg',
phoneNumber: {
one: 'eeee',
two: 'ccc'
}
}
}
let subPro = pro[key];
这里有点问题,不过自己解决了
解决了,我还得再多学习一下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: 'csdn',
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 replaceKey = (src, pro) => {
let res = {};
Object.keys(pro).forEach(key=>{
let val = pro[key];
if ({}.toString.call(val) === '[object String]') {
if (src.hasOwnProperty(val)) {
res[key] = src[val];
}
} else if ({}.toString.call(val) === '[object Object]') {
let subPro = pro[key];
if (src.hasOwnProperty(key)) {
if (Array.isArray(src[key])) {
let arr = [];
src[key].forEach(e=>{
arr.push({...replaceKey(e, subPro)});
});
res = arr;
} else {
res = replaceKey(src[key], subPro);
}
} else {
res[key] = replaceKey(src, subPro);
}
}
})
return res;
}
console.log(replaceKey(data, property));