-
RISEBY
这是一种递归方法,我检查所有名称,如果一个名称出现两次,我就中断迭代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))
-
翻翻过去那场雪
您可以对收集可见名称的 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));
-
慕标琳琳
尝试一下这个我提取所有"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.lengthconsole.log("Unique?",unique,names.join(","))