3 回答
TA贡献1856条经验 获得超5个赞
这是一种递归方法,我检查所有名称,如果一个名称出现两次,我就中断迭代
const reduxTree = { units: [{ name: 'ROOT', units: [{ name: 'ORG1', units: [], entities: [{ name: 'LE1', portfolios: [{ name: 'PO1', }] }], }, { name: 'ORG2', units: [], entities: [{ name: 'LE2', portfolios: [{ name: 'PO2', }] }], } ], entities: [{ name: 'LE3', portfolios: [{ name: 'PO3', }] }], }] };
const mySet = new Set();
function validateTree(obj){
if(!obj || obj.length == 0){
return true;
}
if(mySet.has(obj[0].name)){
return false;
} else {
return validateTree(obj[0].units) && validateTree(obj[0].entities) && validateTree(obj[0].portfolios)
}
}
console.log(validateTree(reduxTree.units))
TA贡献2065条经验 获得超13个赞
您可以对收集可见名称的 a 进行闭包,并对要分离的对象和对象的其余部分Set进行解构。name
检查名称后,如果在集合中,则返回 false,否则将名称添加到集合中并迭代并检查其余属性。
const
hasUniqueNames = (object, names = new Set) => {
const c = ({name, ...rest }) => {
if (name !== undefined) if (names.has(name)) return false;
names.add(name);
return Object.values(rest).every(v => !v || typeof v !== 'object' || c(v));
};
return c(object);
},
reduxTree = { units: [{ name: 'ROOT', units: [{ name: 'ORG1', units: [], entities: [{ name: 'LE1', portfolios: [{ name: 'PO1' }] }] }, { name: 'ORG2', units: [], entities: [{ name: 'LE2', portfolios: [{ name: 'PO2' }] }] }], entities: [{ name: 'LE3', portfolios: [{ name: 'PO3' }] }] }] },
result = hasUniqueNames(reduxTree);
console.log(hasUniqueNames(reduxTree));
TA贡献1830条经验 获得超9个赞
尝试一下这个
我提取所有"name":"<name>"并使用 Set 来查看它们是否是唯一的
const reduxTree = { units: [{ name: 'ROOT', units: [{ name: 'ORG1', units: [], entities: [{ name: 'LE1', portfolios: [{ name: 'PO1', }] }], }, { name: 'ORG2', units: [], entities: [{ name: 'LE2', portfolios: [{ name: 'PO2', }] }], } ], entities: [{ name: 'LE3', portfolios: [{ name: 'PO3', }] }], }] }
const names = [...JSON.stringify(reduxTree).matchAll(/"name":"(\w+)"/g)].map(m => m[1])
const unique = new Set(names).size === names.length
console.log("Unique?",unique,names.join(","))
添加回答
举报