介绍
根据模板,自动对一个 JS 对象的字段进行裁剪、添加或更新字段内容。
比如,做一个设置功能,其设置的数据(一个对象)存储在 localStorage 中,如果增加了设置项或删除设置项、或修改字段,如果打开 F12 清除 localStorage,会丢失上次设置的数据,过程繁琐和麻烦。
演示效果
// 定义一个模板
const settingTempl = {
themeMode: "dark",
themeColor: "#409eff",
openToolKits: true,
githubPostion: "left",
openPager: false,
contentWidth: 50,
cabinet: {
left: 0,
right: 0,
break: false,
remote: true,
pinLeft: false,
pinRight: false,
width: 17.5
},
background: {
filter: 6,
src: ""
}
};
// 获取 localStorage 存储的对象
const store = JSON.parse(localStorage.getItem('setting'));
// 对比模板,裁剪、添加对象字段或更新字段内容
const newStore = refactorObjectProperties(store, settingTempl);
// 重新存储到 localStorage 中,不影响没有变化的字段
localStorage.setItem('setting', JSON.stringify(newStore));
函数实现
/**
* 对一个对象的字段进行裁剪或添加
*
* @param source 要被裁剪或添加字段的对象
* @param objectTemplate 一个对象,根据该模板(对象)对 store 进行裁剪或添加字段
* @returns
*/
export function refactorObjectProperties(source, objectTemplate) {
const sourceKeys = Object.keys(source);
const templateKeys = Object.keys(objectTemplate);
// 长度不相等,存在缺少的字段
if (sourceKeys.length !== templateKeys.length) {
// store 的字段长于模板的字段,说明要进行剔除
if (sourceKeys.length > templateKeys.length) {
sourceKeys.forEach(sourceKey => {
const nonentity = templateKeys.find(templateKey => templateKey === sourceKey);
if (!nonentity) {
Reflect.deleteProperty(source, sourceKey);
}
});
// store 字段小于模板的字段,说明要增加
} else if (sourceKeys.length < templateKeys.length) {
// 对 store 每一个字段进行检查
templateKeys.forEach(templateKey => {
// 找到 store 中不存在的字段
const nonentity = sourceKeys.find(sourceKey => templateKey === sourceKey);
if (!nonentity) {
// 从模板中拿对应的字段添加到 store 中
source[templateKey] = objectTemplate[templateKey];
} else {
// 字段都存在,检查其字段是否是 Object 类型,再检查是否长度相等,进行递归
if (typeof objectTemplate[templateKey] === "object") {
refactorObjectProperties(source[templateKey], objectTemplate[templateKey]);
}
}
});
}
// 长度相等,查看它对象下是否有缺少的字段
} else {
templateKeys.forEach(templateKey => {
if (typeof objectTemplate[templateKey] === "object") {
if (typeof source[templateKey] !== "object") {
source[templateKey] = objectTemplate[templateKey];
}
refactorObjectProperties(source[templateKey], objectTemplate[templateKey]);
} else if (typeof objectTemplate[templateKey] !== "object") {
if (typeof source[templateKey] === "object") {
source[templateKey] = objectTemplate[templateKey];
}
}
});
}
return source;
}
标签:const,objectTemplate,裁剪,templateKeys,templateKey,source,字段,refactorObjectPropert
From: https://www.cnblogs.com/Himmelbleu/p/17149425.html