Home Web Front-end JS Tutorial How to merge array objects with the same ID by type and allocate amounts using JavaScript?

How to merge array objects with the same ID by type and allocate amounts using JavaScript?

Apr 04, 2025 pm 03:00 PM
red

How to merge array objects with the same ID by type and allocate amounts using JavaScript?

This article describes how to use JavaScript to process an array, merge objects with the same ID into a new object, and allocate the amount to different fields according to different types (breakfast, Chinese, dinner).

Suppose we have an array of multiple objects, each with id , jine (amount) and type (type) fields. The goal is to convert these data into another format, where the data corresponding to each id is merged into one object, and jine value is assigned to jine1 (breakfast), jine2 (Chinese food), and jine3 (dinner) fields according to type .

Raw data:

 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 format:

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

To achieve this, we can use the reduce method to iterate over the array and create a new object to store the results.

Solution:

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

console.log(result); // output array in target format
Copy after login

This code first uses the reduce method to convert the original array into an object, the key is id , and the value is an object containing jine1 , jine2 , and jine3 . Then use the Object.values ​​method to convert the object into an array. In the reduce method, we check whether the current id exists in acc , if it does not exist, create a new object, and assign jine value to the corresponding field according to type .

This method avoids the use of Object.groupBy and find methods, improves the readability and efficiency of the code, and handles data merging and amount allocation more directly. It is also more robust because there is no need to deal with cases where find method may return undefined .

The above is the detailed content of How to merge array objects with the same ID by type and allocate amounts 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)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
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)

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

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

Using Dicr/Yii2-Google to integrate Google API in YII2 Using Dicr/Yii2-Google to integrate Google API in YII2 Apr 18, 2025 am 11:54 AM

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to configure slow query log in centos redis How to configure slow query log in centos redis Apr 14, 2025 pm 04:54 PM

Enable Redis slow query logs on CentOS system to improve performance diagnostic efficiency. The following steps will guide you through the configuration: Step 1: Locate and edit the Redis configuration file First, find the Redis configuration file, usually located in /etc/redis/redis.conf. Open the configuration file with the following command: sudovi/etc/redis/redis.conf Step 2: Adjust the slow query log parameters in the configuration file, find and modify the following parameters: #slow query threshold (ms)slowlog-log-slower-than10000#Maximum number of entries for slow query log slowlog-max-len

What files do you need to modify in HDFS configuration CentOS? What files do you need to modify in HDFS configuration CentOS? Apr 14, 2025 pm 07:27 PM

When configuring Hadoop Distributed File System (HDFS) on CentOS, the following key configuration files need to be modified: core-site.xml: fs.defaultFS: Specifies the default file system address of HDFS, such as hdfs://localhost:9000. hadoop.tmp.dir: Specifies the storage directory for Hadoop temporary files. hadoop.proxyuser.root.hosts and hadoop.proxyuser.ro

Tips for using HDFS file system on CentOS Tips for using HDFS file system on CentOS Apr 14, 2025 pm 07:30 PM

The Installation, Configuration and Optimization Guide for HDFS File System under CentOS System This article will guide you how to install, configure and optimize Hadoop Distributed File System (HDFS) on CentOS System. HDFS installation and configuration Java environment installation: First, make sure that the appropriate Java environment is installed. Edit /etc/profile file, add the following, and replace /usr/lib/java-1.8.0/jdk1.8.0_144 with your actual Java installation path: exportJAVA_HOME=/usr/lib/java-1.8.0/jdk1.8.0_144exportPATH=$J

See all articles