JSON解析-再也不用后台改键名改值名

2次阅读

共计 741 个字符,预计需要花费 2 分钟才能阅读完成。

// 声明
function transTOTree(arr, rule) {
arr.forEach(item => {
rule.forEach(map => {
for (let key in map) {
let newValue = map.oldKey ? item[map.oldKey] : ”;
if (map.newValue) {
newValue = map.newValue(newValue);
}
item[map.newKey] = newValue;
}
})

if (item.children && item.children.length > 0) {
transTOTree(item.children, rule);
}
});
return arr;
}
// 参数
var params = [{
oldKey: “name”,
newKey: “title”,
newValue: v => {
return v;
}
},
{
oldKey: “is”,
newKey: “checked”,
newValue: v => {
return v ? 1 : 0;
}
}
]

// 模拟数据
var oldData = [{
name: 1,
is: 1,
children: [{
name: 11,
is: 1,
children: [{
name: 1111,
is: 0,
}]
}, {
name: 12,
is: 0,
}]
}, {
name: 2,
is: 1,
}]

// 调用
console.log(transTOTree(oldData, params))

// 输出
[{
title: 1,
checked: true,
children: [{
title: 11,
checked: true,
children: [{
title: 1111,
checked: false,
}]
}, {
title: 12,
checked: false,
}]
}, {
title: 2,
checked: true,
}]

正文完
 0