


How to handle duplicate IDs in JavaScript array objects and assign different values?
Cleverly solve the problem of duplicate ID in JavaScript array objects
This article provides an efficient JavaScript method for processing duplicate IDs in array objects and assigning different values to objects with the same ID.
Suppose we have an array object containing duplicate IDs:
const list = [ { id: 1, name: 'Xiao Ming' }, { id: 1, name: 'Xiaohong' }, { id: 2, name: 'Xiaoqiang' }, { id: 3, name: 'Xiao Zhang' }, { id: 4, name: 'Xiaolan' }, { id: 1, name: 'Xiaoqing' }, { id: 4, name: 'Xiaoqing' } ];
Our goal is to add a value
attribute to each object with a duplicate ID and give it a different boolean value (true or false). The final result should be as follows:
const list = [ { id: 1, name: 'Xiao Ming', value: true }, { id: 1, name: 'Xiaohong', value: false }, { id: 2, name: 'Xiaoqiang' }, { id: 3, name: 'Xiao Zhang' }, { id: 4, name: 'Xiaolan', value: true }, { id: 1, name: 'Xiaoqing', value: true }, { id: 4, name: 'Xiaoqing', value: false } ];
To achieve this, we can use one object to track the number of occurrences of the ID and use another object to record the value that each ID has been assigned.
The following is the implementation code:
const list = [ { id: 1, name: 'Xiao Ming' }, { id: 1, name: 'Xiaohong' }, { id: 2, name: 'Xiaoqiang' }, { id: 3, name: 'Xiao Zhang' }, { id: 4, name: 'Xiaolan' }, { id: 1, name: 'Xiaoqing' }, { id: 4, name: 'Xiaoqing' } ]; const idCounts = {}; const idValues = {}; list.forEach(item => { idCounts[item.id] = (idCounts[item.id] || 0) 1; }); list.forEach(item => { if (idCounts[item.id] > 1) { if (!idValues[item.id]) { idValues[item.id] = true; } item.value = idValues[item.id]; idValues[item.id] = !idValues[item.id]; } }); console.log(list);
This code first counts the number of times each ID appears, then iterates over the array, adds value
attributes to objects with repeated IDs, and alternately assigns true and false values. The idValues
object ensures that subsequent objects with the same ID will get different boolean values. This method is simple and efficient, easy to understand and maintain.
The above is the detailed content of How to handle duplicate IDs in JavaScript array objects and assign different values?. For more information, please follow other related articles on the PHP Chinese website!

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

The default playback control style of HTML video cannot be modified directly through CSS. 1. Create custom controls using JavaScript. 2. Beautify these controls through CSS. 3. Consider compatibility, user experience and performance, using libraries such as Video.js or Plyr can simplify the process.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools
