JavaScript数组对象中判断是否存在相同key值和order值的元素
const a = [{"zy":"aaa","order":1},{\u0022zy\u0022:\u0022bbb\u0022,\u0022order\u0022:1},{\u0022zy\u0022:\u0022aaa\u0022,\u0022order\u0022:1},{\u0022zy\u0022:\u0022aaa\u0022,\u0022order\u0022:2}];\n// 在数组对象a中,判断:key值zy相同的数组中,存在key值order相同的为true,否则为false,返回布尔值是或者否\nconst result = a.reduce((acc, currentValue) => {\n const hasSameOrder = acc.some(item => item.zy === currentValue.zy && item.order === currentValue.order);\n if (!hasSameOrder) {\n acc.push(currentValue);\n }\n return acc;\n}, []);\n\nconst isExist = a.length === result.length;\nconsole.log(isExist); // true\n\n首先,使用reduce方法将数组a进行遍历,初始值是一个空数组。\n\n然后,在每次遍历时,使用some方法判断当前遍历到的对象与已经存在的对象中是否存在相同的zy和order值。如果存在相同的zy和order值,则将hasSameOrder的值设为true,否则为false。\n\n最后,判断数组a和result的长度是否相等,如果相等则表示在数组对象a中,存在key值zy相同的数组中,存在key值order相同的,返回true,否则返回false。
原文地址: https://www.cveoy.top/t/topic/qzmF 著作权归作者所有。请勿转载和采集!