JavaScript: Combine objects in an array

In my current project, I am handling an array of change logs, each representing a field change in an item.

Here is how my changeLogArray appears:

changeLogArray=[{"ItemNo":"01", "Field":"Price","OldValue":"100","NewValue":"200","CreatedDate":"17/10/2020"},
{"ItemNo":"01", "Field":"Price","OldValue":"200","NewValue":"300","CreatedDate":"18/10/2020"},
{"ItemNo":"01", "Field":"Price","OldValue":"300","NewValue":"400","CreatedDate":"19/10/2020"},
{"ItemNo":"01", "Field":"Name","OldValue":"A","NewValue":"B","CreatedDate":"19/10/2020"}]

I aim to consolidate the changes in the Price field into a single row with the OldValue from the first record and NewValue from the last record (ordered by CreatedDate).

[{"ItemNo":"01", "Field":"Price","OldValue":"100","NewValue":"400","CreatedDate":"19/10/2020"},
{"ItemNo":"01", "Field":"Name","OldValue":"A","NewValue":"B","CreatedDate":"19/10/2020"}]

The approach I have taken so far involves filtering out records where Field is not 'Selling Price', creating separate arrays for Selling Price changes and other changes, and then processing these arrays to achieve the desired result.

var lstToDisplayNotSellingPrice = changeLogArray.filter(item => {
    return item.Field != 'Selling Price'
})

var lstToDisplaySellingPrice  = changeLogArray.filter(item => {
    return item.Field == 'Selling Price'
})

var resultChangeLogSellingPrice = []

changeLogArray.forEach((item, index) =>{
    var distinctItemIndex
    if(index == 0 || item.ItemNo != lstToDisplaySellingPrice[index-1].ItemNo){
        resultChangeLogSellingPrice.push(item)
        distinctItemIndex = index
    }else{
        if(item.FieldLevel == lstToDisplaySellingPrice[index-1].ItemNo){
            resultChangeLogSellingPrice.pop()
            var itemLog = lstToDisplaySellingPrice[index-1]
            itemLog.NewValue = item.NewValue
            itemLog.CreatedDate = item.CreatedDate
            resultChangeLogSellingPrice.push(itemLog)
        }
    }
});

I followed this method to segregate Selling Price changes, update the necessary logs, and then combine both sets of changes into the final result array.

Answer №1

To efficiently group items based on their CreatedDate, one can create an array of sorted objects using the ItemNo and Field attributes.

If a value is missing, update it with the appropriate NewValue and CreatedDate.

const
    data = [{ ItemNo: "01", Field: "Price", OldValue: "100", NewValue: "200", CreatedDate: "17/10/2020" }, { ItemNo: "01", Field: "Price", OldValue: "200", NewValue: "300", CreatedDate: "18/10/2020" }, { ItemNo: "01", Field: "Price", OldValue: "300", NewValue: "400", CreatedDate: "19/10/2020" }, { ItemNo: "01", Field: "Name", OldValue: "A", NewValue: "B", CreatedDate: "19/10/2020" }],
    result = Object.values(data.reduce((r, o) => {
        const key = ['ItemNo', 'Field'].map(k => o[k]);
        r[key] ??= { ...o };
        r[key].NewValue = o.NewValue;
        r[key].CreatedDate = o.CreatedDate;
        return r;
    }, { }));
   
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Counter Fails to Increase When Items are Added to Cart

Hello there! I recently ran into a coding issue while trying to remove the side bar cart popup on my website. After making some modifications, I noticed that the item counter in the cart no longer increments when using the quick add button. Oddly enough, t ...

Analyzing Passwords for Redirection

Greetings to all! I trust everyone is doing well. I have developed a react application that features 2 password fields, each with validation using regular expressions. Upon successful validation of both passwords, the application will automatically redirec ...

What is the process of sending Firebase topic notifications through Node.js and Express?

As an Android developer, I am trying to send notifications to all users in my app who are subscribed to the topic named ALL_USER. However, I have encountered difficulties in sending notifications to that specific topic. Thank you in advance for your assis ...

Error message: Impossibile to locate module 'formik' in 'C:Live projectsNew folder (2)src\_metronicpartialsmodalscreate-app'

"dependencies": { "@formatjs/intl-pluralrules": "^4.0.28", "@formatjs/intl-relativetimeformat": "^9.1.7", "@fortawesome/fontawesome-free": "^5.15.3", "@popperjs/core": "~2.10.1", "animate.css": "^4.1.1", "apexcharts": "^3.27.1", ...

npm socket.io installation failed due to node version being less than 0.10.0

Having trouble installing socket.io on my BeagleBone Black because my system is using Node v0.8.22, but the required version for installation is above 0.10.0. Unfortunately, I am unable to upgrade my Node. /usr/bin/ntpdate -b -s -u pool.ntp.org cd /var/li ...

I need help figuring out the proper way to establish an indexing path in cosmos db using the nodejs sdk

I'm currently facing a challenge with setting up the indexing policy for one of my cosmosdb containers. Within my cosmosdb, I have a container that stores information about user sessions. Using the node sdk, I am defining the containers, partition key ...

Guide on how to capture tweets from particular Twitter profiles

I'm currently experimenting with the twitter npm package to stream tweets from specific accounts, but I'm facing some challenges. After reviewing the Twitter API documentation, I must admit that I am a bit perplexed. To fetch details about a pa ...

Excessively Running Firebase Function Due to setInterval Usage

My Firebase function is set to run every 20 minutes using setInterval, but it seems to be executing more frequently than expected. Here is an excerpt from my code: try { const response = await axios.get( "https://ll.thespacedevs.com/2.0.0/ ...

Having trouble with arrays in JavaScript - receiving TypeError when trying to set a property

Issue: An error has occurred - Uncaught TypeError: Cannot set property '0' of undefined Snippet of relevant code: var field = new Array(6); for(var x=0; x<field.length; x++){ field[x] = new Array(12); for(var y=0; y<field[x].length; y ...

Generating an array in Swift filled with randomly generated boolean values

I am currently working on a function that requires me to generate an array of random boolean values, but I am struggling to implement this logic within the function. Any guidance or assistance on this matter would be greatly appreciated. Unfortunately, I ...

Angular 11 - New Script Inserted into scripts Directory and Linked in angular.json Configuration

I just added a new script file in the src/assets/scripts directory and updated its path in the scripts section of angular.json. My question is: Will I need to restart ng serve for the changes to take effect the next time the application is run? Thank you ...

The filter function in JavaScript's Array is malfunctioning on Internet Explorer version 7

My web application includes a jQuery plugin that is functioning correctly in Internet Explorer 10 and 11. However, it is not working in IE 7. Upon investigation, I discovered that the value of the filter method is showing as undefined. The line of code th ...

PHP and MySQL - Experimenting with Passing Query Variables from MySQL Fetch Array Using Page URLs

I have a script in place that fetches a row from a MySQL table and is designed to pass specific variables from that row to a subsequent page for user updating within a form. Within the script, I am attempting to pass the variables to the next page using t ...

What is the method for sending parameters to PHP from an HTML file using AJAX?

My protfolio.html file contains a table #gallery with different categories. I want to dynamically update the content of the #gallery based on the selected category using ajax. I have a php file that scans a specific folder for images related to the categor ...

Arrow smoothly sliding beneath the selected tab in the active menu

Here is a reference picture. https://i.sstatic.net/wsp6R.png I am trying to create a slide effect for my arrow when clicking on different menu items. The arrow should move over the active menu item. By default, the arrow should point to the active menu. ...

What is the best way to acquire an ID that is generated dynamically?

Being new to javascript and ajax, I am facing a challenge. I have a while loop with 2 buttons, both of which seem to function correctly, except for one small issue... The product-id is only being passed for the first or last element in the loop. How can I ...

When viewing on mobile devices, the hover effect in responsive web design

While working on a responsive website, I encountered some challenges. I have a Div containing an image and some information. When a user hovers over this div, the background changes and 3 buttons appear. However, the issue arises when using a mobile devi ...

Utilizing Vue's computed function to filter values from a JSON dataset

How do I efficiently filter an array of JSON data? Here is the code snippet: <div v-if="vacciCounter"> <b-card no-body class="mb-2" v-for="(stateObject, state) in filteredList" v-bind:key="state"& ...

What is the best way to access AngularJS Service code from an Android webview?

I've been attempting to initiate contact with an AngularJS service through the Android webview component, but I haven't had any luck so far. Do you have any suggestions on how I can achieve this? Here is the JavaScript code that I've been t ...

Utilize a select box to toggle between enabling and disabling options

Could someone please help me with enabling and disabling a text field based on a select box option? I'm not sure if I have written the code correctly below. If there are any errors, please correct me. <body> <table width="500" border="1"> ...