Discover the perfect method for combining two objects while updating any empty values with a new specified value. Furthermore, in the case where the new value is also

My task involves working with an array of objects where each time I select a value, it gets pushed into the array. My goal is to merge two objects that share the same key "code" and remove any empty values.

(4) [{…}, {…}, {…}, {…}]
0: {code: "abc", value: "", access: "A"}
1: {code: "abc", value: "ok", access: ""}
2: {code: "def", value: "xyz", access: ""}
3: {code: "def", value: "", access: "B"}

The desired output should be:
(2) [{…},{…}]
0: { code: "abc", value: "ok", access: "A"}
1: {code: "def", value: "xyz", access: "B"}

I have attempted using the spread operator but it seems to not work as expected. Any suggestions or help would be greatly appreciated.

Answer №1

If you're looking for a solution, consider using the Object.assign(..) method instead of .reduce(). Here's an alternative approach:

const data = [
  {id: 1, name: "Alice", age: 30},
  {id: 2, name: "Bob", age: 35},
  {id: 1, name: "Charlie", age: 28}
];

const updatedData = data.reduce((acc, current) => {
  const found = acc.find(item => item.id === current.id);
  if (found) {
    Object.assign(found, current);
  } else {
    acc.push(current);
  }
  return acc;
}, []);

console.log(updatedData);

While this code snippet may appear to work with certain inputs, it does not account for all potential scenarios. Be cautious as it overwrites existing values during the merge process.

To address this issue, incorporate additional verification checks within the conditional statements to tailor the merging behavior to your specific requirements.

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

Error: Module 'config' not found by Jest

I have encountered an issue while using Jest to test my api calls file. When running a simple test, I received an error Cannot find module 'config' from 'api.service.js'. This error is related to the import statement at the top of my ap ...

What is the best approach to concurrently update a single array from multiple functions?

In my React app, I have a form with various input fields and checkboxes. Before making an API call to submit the data, I have functions set up to check if any fields are left blank or unchecked. These check functions are triggered when the form button is ...

Storing a class method in a variable: A guide for JavaScript developers

I am currently working with a mysql connection object called db. db comes equipped with a useful method called query which can be used to execute sql statements For example: db.query('SELECT * FROM user',[], callback) To prevent having to type ...

Struggling to display a chart using angular-chart

I am facing an issue with rendering my chart. I have followed the instructions provided on the GitHub page of angular-chart.js. I have created a plunker to showcase my problem: http://plnkr.co/edit/x7XJhxxvYMzWr3u7lBcJ?p=preview Although I can access and ...

blur event triggered on a cell within a table

Currently, I am using the code snippet below to populate data using a data table. My goal is to be able to edit the data in one of the columns and then validate the value after editing using the onblur event. I attempted to call the onblur event on the t ...

React - Refreshing a component with the help of another component

I've created a NavBar component that contains a list of links generated dynamically. These links are fetched from the backend based on specific categories and are stored within a child component of NavBar named DrawerMenu. The NavBar itself is a chil ...

What is the most effective way to exchange data among multiple React applications?

I am looking for a solution to securely share data among multiple applications, with some parts of the data being secure and others not. I have explored options like IndexedDB and localStorage, but they don't work in all browsers, especially in incogn ...

Fan Animation in CSS

I have three unique images that I would like to animate in a fan-like manner consecutively. I prefer not to merge the images in Photoshop, as I want them to be displayed one after the other. Here is the code snippet (dummy images are used): .bannerimg ...

Enhancing quiz results with intricate input forms using JavaScript

I am currently working on an online quiz and the code is functioning properly. However, I would like to display the scores of each user. As a beginner in Javascript, I have been developing this quiz for a friend, and it has been a learning experience for m ...

Updating the output without the need for a page refresh following the insertion of data into the database

I'm interested in enhancing the interactivity of this section in my code. Currently, I utilize a form to send announcements via ajax to a php file which successfully updates my database. The table displays the data effectively. However, I want these c ...

Obtain a specific text value as a variable using Google Tag Manager

In my quest to extract the dynamic "sku" value from GTM, I am faced with a challenge. This particular value is unique for each product page. Below is an example of how the code appears on the page: <script type="application/ld+json"> { "@context" ...

Restrict access to table records by specifying an array of row identifiers

Hi everyone, I've encountered a small issue. Just to provide some background, I have a table with checkboxes. Each row in the table has an associated ID, and when selected, I receive an array like this: const mySelectedRoles = [1997, 1998, 1999] Once ...

Encountering issues with running the 'npm run serve' command locally in a Vue project

Trying to develop an app with Vue, I used the npm command. However, when I executed "npm run serve," the messages showed me that I should be running the app at "http://localhost:8080/" and not on "x86_64-apple-darwin13.4.0:". Is there a way to fix this by ...

Exploring Passportjs Callbacks and parsing arguments

I'm struggling to grasp the concept behind the custom callback in Passport.js. I'm not sure why it requires (req, res, next) at the end. Shouldn't these values be obtained from closure? app.get('/login', function(req, res, next) { ...

Can OR be utilized within a find operation?

I am currently developing a social media platform similar to Facebook using Express and MongoDB. One of the features I'm working on is adding friends to user profiles. When a user clicks on a button that says "Send Friend Request" on another user&apos ...

"Step-by-step guide on using JavaScript to print a PDF file stored locally

As an illustration, I have a local PDF file with 6 pages. When using the window.print() function, only one page is displayed in print preview regardless of what is shown in the browser. Instead of just one page, all pages should be visible in print previ ...

Encountering issues with installing @vue/cli on Linux Ubuntu

Currently facing an issue while attempting to install the Vue CLI on Ubuntu (WSL). After running both yarn add global @vue/cli and npm install @vue/cli --global, it seems like the commands were successful. However, upon checking the version using vue --v ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

HTML TABS: Make the first TAB automatically selected

I've been experimenting with tabbing in HTML using a tutorial I found on W3SCHOOLS. While the source code provided works fine, I'm encountering an issue with automatically selecting the first tab by default. The tutorial doesn't cover this, ...

JavaScript - Automatic memory management following the execution of functions

After doing some research on garbage collection in JavaScript, I came across information stating that local variables of functions are collected once the function has returned (except for cyclical references which require breaking circles for the GC to fun ...