Comparing two arrays of objects and updating the first object when a matching value is found in the second object: A guide

Trying to update the first array based on matching data from the second array. Encounter an error with forEach loop.

First array:

const data = [{
    id: 1,
    name: "Alice"
  }, {
    id: 2,
    name: "Bob"
  }, {
    id: 3,
    name: "Charlie"
  }
]

Second array:

const newData = [{
  id: 1,
  name: "Alex"
}, {
  id: 2,
  name: "Bob"
}]

Expected output:

const result = [{
    id: 1,
    name: "Alex"
  }, {
    id: 2,
    name: "Bob"
  }, {
    id: 3,
    name: "Charlie"
  }
]

Answer №1

Discover the corresponding information in response for each element within the body. If no match is found, retain the original information without alteration; otherwise, merge them together to create a new object.

Addressing the observation made by @trincot regarding the presence of two different time formats in the data. I have tackled this issue by utilizing String#padStart; however, it is recommended to address this inconsistency at the data source.

body.map(originalSlot => {
    const slotInfo = response.find(
      ({ slot }) => slot === originalSlot.slot.padStart(5, 0)
    );

    if (!slotInfo) {
        return originalSlot;
    }

    return { ...originalSlot, ...slotInfo, slot: originalSlot.slot };
});

Give it a try:

const body = [
  {
    slot: '9:00',
    status: 'Available',
    clientName: '',
    doctorName: ''
  },
  {
    slot: '9:30',
    status: 'Available',
    clientName: '',
    doctorName: ''
  },
  {
    slot: '1:00',
    status: 'Available',
    clientName: '',
    doctorName: ''
  },
  {
    slot: '1:30',
    status: 'Available',
    clientName: '',
    doctorName: ''
  }
];

const response = [
  {
    clientName: 'John Doe',
    doctorName: 'Paul Pierce',
    slot: '09:00',
    status: 'Not Available'
  },
  {
    clientName: 'James Bond',
    doctorName: 'Chris Paul',
    slot: '01:00',
    status: 'Not Available'
  }
];

const results = body.map(originalSlot => {
    const slotInfo = response.find(
    ({ slot }) => slot === originalSlot.slot.padStart(5, 0)
  );

    if (!slotInfo) {
        return originalSlot;
    }

    return { ...originalSlot, ...slotInfo, slot: originalSlot.slot };
});

console.log(results);

Answer №2

Give this method a shot:

const initialList = [
  {
    slot: "9:00",
    status: "Available",
    clientName: "",
    doctorName: "",
  },
  {
    slot: "9:30",
    status: "Available",
    clientName: "",
    doctorName: "",
  },
  {
    slot: "1:00",
    status: "Available",
    clientName: "",
    doctorName: "",
  },
  {
    slot: "1:30",
    status: "Available",
    clientName: "",
    doctorName: "",
  },
];

const updatedList = [
  {
    clientName: "John Doe",
    doctorName: "Paul Pierce",
    slot: "9:00",
    status: "Not Available",
  },
  {
    clientName: "James Bond",
    doctorName: "Chris Paul",
    slot: "1:00",
    status: "Not Available",
  },
];

function timeStringParser(timeStr) {
  let [hour, minutes] = timeStr.split(":");
  return +(hour + minutes);
}

initialList.forEach((item) =>{
  updatedList.some((item2) =>{
    if (timeStringParser(item.slot) == timeStringParser(item2.slot)) {
      Object.assign(item, item2);
    }
  });
});

console.log(initialList);

Answer №3

If you decide to adjust the response array slots to match the body format, you can use a straightforward method like this:

Here's a simple and easy-to-understand approach:

let result = [...body];

for (let time of body) {
    let responseSlot = response.find(s => s.slot == time.slot);

    if (responseSlot) {
        result = [...result.filter(t => t != time), responseSlot];
    }
}

This method will generate the following output:

[
  { slot: '9:30',
    status: 'Available',
    clientName: '',
    doctorName: ''
  },
  { slot: '1:30',
    status: 'Available',
    clientName: '',
    doctorName: ''
  },
  {
    clientName: 'John Doe',
    doctorName: 'Paul Pierce',
    slot: '9:00',
    status: 'Not Available'
  },
  {
    clientName: 'James Bond',
    doctorName: 'Chris Paul',
    slot: '1:00',
    status: 'Not Available'
  }
]

In this scenario, update the response array to this:

const response = [{
    clientName: "John Doe",
    doctorName: "Paul Pierce",
    slot: "9:00",
    status: "Not Available"
}, {
    clientName: "James Bond",
    doctorName: "Chris Paul",
    slot: "1:00",
    status: "Not Available"
}]

Answer №4

In a recent discussion, it was noted that the following code snippet may be relevant to your needs:

const result = [];
Object.keys(body).forEach((key) =>
  key in response ? (result[key] = response[key]) : (result[key] = body[key])
);

The idea behind this approach is to iterate through all the properties of the body object. If a property value matches with the corresponding property value in the response object, it will update the value of that property in the body object. Otherwise, it will leave the values in the body object unchanged.

For more information, you can refer to the previous discussion at: Update an object with matching properties and ignore new properties

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

Converting an array of objects into an array of Objects containing both individual objects and arrays

I am dealing with an object const response = { "message": "story records found successfully", "result": [ { "created_AT": "Thu, 13 Jan 2022 17:37:04 GMT", ...

Leveraging Google Cloud Functions with Next.js (Client-Side Rendering)

Having trouble incorporating firebase cloud functions into my Next.js project, encountering an unfamiliar error. firebase-config.js const firebaseConfig = { apiKey: '~~~', authDomain: '~~', projectId: '~~~', storageBu ...

Ignoring CSS transitions by changing the width property in JavaScript’s element.style

When attempting to create a smooth progress bar animation by adjusting the width using document.querySelector('#mydiv').style.width = '20%', I noticed that the new width is updated instantly rather than transitioning smoothly. It seems ...

unable to retrieve the value of this.table property within a JavaScript class

In my JavaScript code, I have created a class that generates a MySQL model like so: class Model { constructor(options = {}, table) { this.options = options; this.table = table; this.create(); } create() { let queryString = `INSERT INT ...

Developing an IF statement in JavaScript that relies on hexadecimal color values

I've created a JavaScript code that changes the background color of my webpage every time it loads: document.getElementById("band").style.background = '#'+(Math.random()*0xFFFFFF<<0).toString(16); To improve visibility, I am aiming t ...

Ways to implement StackNavigator along with Redux?

Is there anyone who can assist me in integrating StackNavigator and Redux? It seems straightforward, but I'm encountering issues. index.ios.js import React from 'react' import { AppRegistry } from 'react-native' import { Provi ...

Identifying Matching Array Indexes

Received a POST request on one of my pages, below is an excerpt: [shipCountry] => United States [status] => Accepted [sku1] => test [product1] => Test Product [quantity1] => 1 [price1] => 0.00 The request may vary in size, with product ...

Retrieve the Vue.js JavaScript file from the designated static directory

This is my inaugural attempt at creating a web application, so I am venturing into Vue.js Javascript programming as a newcomer. I have chosen to work with the Beagle Bootstrap template. Within my Static folder, I have a file named app-charts-morris.js whi ...

The compatibility issue between Angular JS variables and Twig is causing functionality problems

issue Currently, I am utilizing a combination of Twig templates and AngularJS. controller public function testAction() { $this->render('AcmeDemoBundle:abc.html.twig'); } javascript code var scotchApp = angular.module('scotch ...

Is there a way to ensure that clicking a link_to only opens a partial once?

These are the files I am working with: _comment.haml %div.comment{ :id => "comment-#{comment.id}" } %hr - if current_user && current_user.id == comment.user_id || current_user && current_user.id == reel_user = link_to " ...

Browserify - combine external modules into a single bundle

I am a complete beginner in the world of browserify. I recently discovered this interesting module called peer-file, which allows for file transfer between two browsers. After reading the Usage section in its readme, I realized I needed to include the scri ...

Each time a page loads, the react useContext feature is causing the web socket connection to reset

I have integrated websockets into various parts of my nextJS application and need to make sure they are accessible everywhere without resetting the socket connection. Whenever the connection is reset, it loses all the rooms it was connected to, causing iss ...

Searching Firebase by using comparison operators on various fields

const FindFiis = async () => { const data: any[] = []; // Firebase query with inequalities on different fields to retrieve docs. // Objective: Select documents where dividendYield is between 8 and 20 and pvp is less than or equal to 1. ...

Efficient Way to Add Elements to a JSON Array using PHP

Struggling to add a new field within a JSON array "filterField": [ { "fieldName": "Tray", "fieldId": 10 }, { ...

Tips for resolving the setAttribute() function error message: "Argument of type 'boolean' is not assignable to parameter of type 'string'"

I am currently working on a function that dynamically updates the HTML aria-expanded attribute based on whether it is true or false. However, when I declare element as HTMLElement, I encounter an error stating Argument of type 'boolean' is not as ...

Is there a way to convert a 2D array into a 3D array using Python?

I am attempting to visualize a two-dimensional array representing a pyramid in three-dimensional space. I could easily achieve this using the mesh() function in Matlab, but I am struggling to do it in Python. import numpy as np import matplotlib.pyplot a ...

Trigger an event when the menu is outside the viewport and then lock the menu to the top of the viewport

I am trying to create a menu element that remains fixed at the top of the browser viewport as the user scrolls, ensuring it is always visible. In my webpage layout, the menu sits below some text in the header initially. Once the user scrolls past the heade ...

Facing a problem with Angular JS where the get method is resulting in a 405 error

Hey there, I have a service that is written with the following method: var GetData = function (token) { $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; var response = $http.get(baseurl + "api/controller/sea ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

Challenge with inserting documents in Mongoose database

I have set up a schema and now I am trying to insert data into a MongoDB collection, but I keep getting an error stating that diagramModel.insert is not defined. Can anyone help me figure out what I did wrong? app.js mongoose.connect('mongodb://lo ...