如何将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来优化上述逻辑。我应该对这个问题使用递归吗?
任何帮助表示赞赏
答案 0 :(得分:0)
您可以使用嵌套的哈希表,并对键/术语使用迭代和递归方法。
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; }