JavaScript 对象数组去重方法 - 如何避免添加重复国家
{"title":"Country = [\n { country: '所有国家', label: 'all'}\n ]\n帮我写个方法在添加对象数组时,去重内容:你可以使用以下方法来在添加对象数组时去重:\n\njavascript\nfunction addCountry(countries, newCountry) {\n // 检查是否已存在相同的国家\n const isDuplicate = countries.some(country => country.country === newCountry.country);\n \n // 如果不存在相同的国家,则添加到数组中\n if (!isDuplicate) {\n countries.push(newCountry);\n }\n \n return countries;\n}\n\n// 示例用法\nconst countries = [\n { country: \'所有国家\', label: \'all\' },\n { country: \'美国\', label: \'USA\' },\n { country: \'中国\', label: \'China\' }\n];\n\nconst newCountry = { country: \'日本\', label: \'Japan\' };\nconst updatedCountries = addCountry(countries, newCountry);\n\nconsole.log(updatedCountries);\n\n\n这个方法会检查新的国家对象是否已经存在于数组中,如果不存在则将其添加到数组中。最后返回更新后的数组。
原文地址: https://www.cveoy.top/t/topic/pLzU 著作权归作者所有。请勿转载和采集!