javascript - 使用递归将数据结构更改为不同的格式
问题描述
我如何将 loadash 用于以下数据结构并获得所需的输出。
我在此递归中使用数组索引的逻辑,因为 terms 属性将是单个元素的数组。
let data = {
users: [
{
terms: ["service|/users"],
conditions: ["view", 'create']
},
{
terms: ["service|/users-details"],
conditions: ["view"]
},
{
terms: ["service|/usersNew"],
conditions: ["view"]
},
{
terms: ["list|searchuser"],
conditions: ["view"]
},
{
terms: ["list|createuser"],
conditions: ["view", "create"]
},
{
terms: ["service|/user-contacts"],
conditions: ["view"]
},
{
terms: ["service|/user-location"],
conditions: ["view"]
},
{
terms: ["page|supplierlist|button|select"],
conditions: ["enable"]
},
{
terms:["page|supplierlist|button|create-new"],
conditions: ["disable"]
}
]
};
class Mapper{
constructor(data){
this.currentIndex = -1;
this.data = this.extractData(data);
}
resolveData(terms, object={}, conditions){
try{
return terms.reduce((result, string) => {
const [key, value] = string.split(/\|(.+)/);
if (value && value.includes('|')) {
result[key] = result[key] || {};
this.resolveData([value], result[key], conditions);
} else {
result[key] = result[key] || [];
this.currentIndex = this.currentIndex + 1;
result[key].push({ [value]: conditions[this.currentIndex] });
}
return result;
}, object);
}catch(error){
throw error
}
}
extractData(data){
try{
let terms = data.users.map(o => o.terms)
terms = [].concat(...terms);
const conditions = data.users.map(o => o.conditions);
return this.resolveData(terms, {}, conditions)
}catch(error){
throw error
}
}
}
const result = new Mapper(data)
console.log(result)
有没有更好的方法通过使用 lodash 来优化上述逻辑。我应该对这个问题使用递归吗?
任何帮助表示赞赏
解决方案
您可以使用嵌套哈希表,并对键/术语使用迭代和递归方法。
var data = { users: [{ terms: ["service|/users"], conditions: ["view", 'create'] }, { terms: ["service|/users-details"], conditions: ["view"] }, { terms: ["service|/usersNew"], conditions: ["view"] }, { terms: ["list|searchuser"], conditions: ["view"] }, { terms: ["list|createuser"], conditions: ["view", "create"] }, { terms: ["service|/user-contacts"], conditions: ["view"] }, { terms: ["service|/user-location"], conditions: ["view"] }, { terms: ["page|supplierlist|button|select"], conditions: ["enable"] }, { terms: ["page|supplierlist|button|create-new"], conditions: ["disable"] }] },
hash = { _: [] },
result;
data.users.forEach(({ terms: { 0: terms }, conditions }) => {
terms.split('|').reduce((r, k) => {
if (!r[k]) {
r[k] = { _: [] };
r._.push({ [k]: r[k]._ });
}
return r[k];
}, hash)._.push(...conditions);
});
result = { currentIndex: data.users.length - 1, data: Object.assign({}, ...hash._) };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- laravel - 无法使用 Supervisor 启动 laravel-echo-server
- php - 从给定路径中删除文件和文件夹
- python - LSTM 在预测和基本事实之间具有系统偏移
- matrix - 在 Maxima 中,如何获得矩阵的行总和?
- java - 在 Primefaces 中导出 .pdf 后如何重定向到其他页面?
- symfony - 使用 FormBuilder 时如何修复“变量不存在”?
- typescript - 可选接口成员的打字稿强制实现
- git - 如何确定您的本地工作目录不包含任何更改?
- python - 通过 python 从 Cloud Foundry 导出数据
- kubernetes - Kubernetes Pod 的自动重启