Table of Contents
JavaScript array element merging: Merge elements with the same ID into one object
Home Web Front-end JS Tutorial How to merge array elements with the same ID into one object using JavaScript?

How to merge array elements with the same ID into one object using JavaScript?

Apr 04, 2025 pm 05:09 PM
switch red

How to merge array elements with the same ID into one object using JavaScript?

JavaScript array element merging: Merge elements with the same ID into one object

In data processing, it is often necessary to merge array elements with the same ID into a single object. This article provides a JavaScript solution to convert array elements with the same ID but different attributes into a new array format.

Original data format:

 const list = [
    { id: "202301", jine: 23, type: "Dinner" },
    { id: "202301", jine: 87.5, type: "Breakfast" },
    { id: "202301", jine: 1065.5, type: "Chinese food" },
    { id: "202302", jine: 10, type: "Dinner" },
    { id: "202302", jine: 181.5, type: "Breakfast" },
    { id: "202302", jine: 633.5, type: "Chinese food" }
];
Copy after login

Target data format:

 const targetList = [
    { id: "202301", jine1: 87.5, jine2: 1065.5, jine3: 23 },
    { id: "202302", jine1: 181.5, jine2: 633.5, jine3: 10 }
];
Copy after login

Solution:

We will use the reduce method to implement data conversion. This method iterates over the array and accumulates each element into a result object.

 const result = Object.values(list.reduce((acc, curr) => {
    const { id, jine, type } = curr;
    if (!acc[id]) {
        acc[id] = { id };
    }
    switch (type) {
        case 'breakfast': acc[id].jine1 = jine; break;
        case 'Chinese food': acc[id].jine2 = jine; break;
        case 'dinner': acc[id].jine3 = jine; break;
    }
    return acc;
}, {}));

console.log(result); // Output target data format
Copy after login

Code explanation:

  1. reduce method: The reduce method iterates over list array and accumulates each element into an object acc .
  2. acc[id] : Use id as key to store data into acc object. If id does not exist, a new object is created.
  3. switch statement: Assign the jine value to jine1 , jine2 or jine3 according to the value of type attribute.
  4. Object.values : Finally, use the Object.values ​​method to convert the acc object into an array to obtain the target data format.

This method is clear and concise, avoiding the use of external libraries, and directly using JavaScript built-in methods to implement data conversion. It's also easier to scale, if you need to deal with more types of dining, just add more case in the switch statement.

The above is the detailed content of How to merge array elements with the same ID into one object using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Debian improves Hadoop data processing speed How Debian improves Hadoop data processing speed Apr 13, 2025 am 11:54 AM

This article discusses how to improve Hadoop data processing efficiency on Debian systems. Optimization strategies cover hardware upgrades, operating system parameter adjustments, Hadoop configuration modifications, and the use of efficient algorithms and tools. 1. Hardware resource strengthening ensures that all nodes have consistent hardware configurations, especially paying attention to CPU, memory and network equipment performance. Choosing high-performance hardware components is essential to improve overall processing speed. 2. Operating system tunes file descriptors and network connections: Modify the /etc/security/limits.conf file to increase the upper limit of file descriptors and network connections allowed to be opened at the same time by the system. JVM parameter adjustment: Adjust in hadoop-env.sh file

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

Summary of phpmyadmin vulnerabilities Summary of phpmyadmin vulnerabilities Apr 10, 2025 pm 10:24 PM

The key to PHPMyAdmin security defense strategy is: 1. Use the latest version of PHPMyAdmin and regularly update PHP and MySQL; 2. Strictly control access rights, use .htaccess or web server access control; 3. Enable strong password and two-factor authentication; 4. Back up the database regularly; 5. Carefully check the configuration files to avoid exposing sensitive information; 6. Use Web Application Firewall (WAF); 7. Carry out security audits. These measures can effectively reduce the security risks caused by PHPMyAdmin due to improper configuration, over-old version or environmental security risks, and ensure the security of the database.

What steps are required to configure CentOS in HDFS What steps are required to configure CentOS in HDFS Apr 14, 2025 pm 06:42 PM

Building a Hadoop Distributed File System (HDFS) on a CentOS system requires multiple steps. This article provides a brief configuration guide. 1. Prepare to install JDK in the early stage: Install JavaDevelopmentKit (JDK) on all nodes, and the version must be compatible with Hadoop. The installation package can be downloaded from the Oracle official website. Environment variable configuration: Edit /etc/profile file, set Java and Hadoop environment variables, so that the system can find the installation path of JDK and Hadoop. 2. Security configuration: SSH password-free login to generate SSH key: Use the ssh-keygen command on each node

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

PostgreSQL performance optimization under Debian PostgreSQL performance optimization under Debian Apr 12, 2025 pm 08:18 PM

To improve the performance of PostgreSQL database in Debian systems, it is necessary to comprehensively consider hardware, configuration, indexing, query and other aspects. The following strategies can effectively optimize database performance: 1. Hardware resource optimization memory expansion: Adequate memory is crucial to cache data and indexes. High-speed storage: Using SSD SSD drives can significantly improve I/O performance. Multi-core processor: Make full use of multi-core processors to implement parallel query processing. 2. Database parameter tuning shared_buffers: According to the system memory size setting, it is recommended to set it to 25%-40% of system memory. work_mem: Controls the memory of sorting and hashing operations, usually set to 64MB to 256M

What is the execution process of Debian Hadoop What is the execution process of Debian Hadoop Apr 13, 2025 am 11:24 AM

The Hadoop task execution process mainly includes the following steps: Submit the job: the user uses the command line tools or API provided by Hadoop on the client machine to build the task execution environment and submit the task to YARN (Hadoop's resource manager). Resource application: After YARN receives the task submission request, it will apply for resources from the nodes in the cluster based on the resources required by the task (such as memory, CPU, etc.). Task Start: Once the resource allocation is completed, YARN will send the task's startup command to the corresponding node. On the node, NodeMana

TigerVNC share file method on Debian TigerVNC share file method on Debian Apr 13, 2025 am 11:45 AM

This article describes how to use TigerVNC to share files on Debian systems. You need to install the TigerVNC server first and then configure it. 1. Install the TigerVNC server and open the terminal. Update the software package list: sudoaptupdate to install TigerVNC server: sudoaptinstalltigervnc-standalone-servertigervnc-common 2. Configure TigerVNC server to set VNC server password: vncpasswd Start VNC server: vncserver:1-localhostno

See all articles