Searching and updating elements within an array object in JavaScript - what's the best way to do this?

I am attempting to locate an element in the target array and update it in the source array.

let sourceArray = [
  {
    "userId": "123",
    "applicationId": "abc",
    "selections": [
      {
        "applicationId": 70930,
        "creationDate": "2021-01-28",
        "responseStatus": "PENDING"
      }
    ]
  }
]

let array2 = [
  {
      "applicationId": 70930,
      "code": "TEST CODE",
      "creationDate": "2021-01-28",
      "submissionDate": "2021-01-29",
      "status": "SUBMITTED",
      "outcomeStatus": "PENDING",
      "responseStatus": "PENDING"
  }
]

The desired outcome is for selections in the source array to be updated with matching elements from array2 based on applicationId

[
  {
    "userId": "123",
    "applicationId": "abc",
    "selections": [
      {
        "applicationId": 70930,
        "code": "TEST CODE",
        "creationDate": "2021-01-28",
        "submissionDate": "2021-01-29",
        "status": "SUBMITTED",
        "outcomeStatus": "PENDING",
        "responseStatus": "PENDING"
      }
    ]
  }
]

I attempted updating the array using the following code snippet

const newArray = sourceArray.map(item => {
  let item2 = array2.find(i2 => item.selections.some(id => i2.applicationId === id.applicationId));
  return item2 ? { ...item, ...item2 } : item;
});

Answer №1

If you're looking for a solution, consider implementing this code snippet. However, don't forget to maintain other relevant information while performing the destructuring process.

let sourceArray = [
  {
    userId: "123",
    applicationId: "abc",
    selections: [
      {
        applicationId: 70930,
        creationDate: "2021-01-28",
        responseStatus: "PENDING",
      },
    ],
  },
];

let array2 = [
  {
    applicationId: 70930,
    code: "TEST CODE",
    creationDate: "2021-01-28",
    submissionDate: "2021-01-29",
    status: "SUBMITTED",
    outcomeStatus: "PENDING",
    responseStatus: "PENDING",
  },
];

sourceArray = sourceArray.map(({ selections, ...otherInfo }) => ({
  ...otherInfo,
  selections: selections.map((selection) => ({
    ...selection,
    ...array2.find((el) => el.applicationId === selection.applicationId),
  })),
}));

console.log(sourceArray)

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

"Utilizing Typescript's keyof operator on its own

I'm grappling with the challenge of creating a type that can utilize the typeof its own keys, but I'm hitting a roadblock. Below is a simplified version of what I'm attempting to achieve: type SpecialType = Record<string, (getter: <K e ...

Extracting data from hidden columns in jQuery DataTables

I am facing an issue with a table where 2 columns are hidden by the dataTables api. When I delete a row, I need to send the data from these columns via ajax to remove it from the database. In the past, I had no problem deleting rows that didn't conta ...

I encountered a "ReferenceError: db is not defined" while trying to call a function in Express.js with MongoDB intergr

The structure of the code is as follows: var express = require('express'); var router = express.Router(); var mongo = require('mongodb').MongoClient; function getData(){ db.collection("collection_name").find({}).toArray(function (er ...

Encountering an error of incorrect format while attempting to ssh into an Azure NextGen VM created by P

Having some trouble creating and sshing into a virtual machine using the Azure nextgen Pulumi API on my Windows 10 machine. After successfully creating the VM, I export the private key to a file for testing purposes. I then adjust the permissions to preve ...

Ways to transmit the appropriate model

Using AJAX, I am sending a model to the server via a POST request. I have defined a model and a controller method for processing it. public class TestDto: BaseDto { [Required] public ProductGalleryDto GalleryProduct { get; set; } public int ...

Executing a console.log statement within an array nested inside a function of an object

Today in school, I learned about objects and how a function inside an object is actually called a method. In my method, I have an array and I'm trying to change a global variable to display a different location in the console.log. However, all I keep ...

Can you explain the use of the 'this' keyword in map() and call() functions?

Recently, I've been revisiting my understanding of how to use call() and map() with a NodeList in JavaScript. It was quite easy to find information on how call() works, and there are plenty of examples of how it can be used with map(). However, whil ...

When a Vue.js Directive is inserted or bound, it actually takes precedence over the click event

Imagine having multiple dropdowns or elements on the page that all utilize a directive called "closable". This directive triggers an expression if the element clicked is outside of the element using the directive. The intended behavior is that when clicki ...

Preventing the need for reassessing ng-options

I have been utilizing ng-options to create a dropdown menu for values that may change infrequently. In a larger example, I have approximately 50 options in the array, and I noticed a decrease in performance each time I made a selection. It seems that ng-op ...

The formBuilder validator pattern seems to be malfunctioning

I am attempting to display a message when the password does not meet the formGroup pattern. Here is how my FormGroup is initialized: this.signupForm = fb.group({ userName: ['', Validators.compose([Validators.required,Validators.pattern(/^&bsol ...

Leverage the new Animation support in RC 5 to animate each item in an *ngFor list sequentially in Angular 2

I have a unique component that retrieves a list of items from the server and then displays that list using *ngFor in the template. My goal is to add animation to the list display, with each item animating in one after the other. I am experimenting with t ...

Using JavaScript, iterate over an array to generate input fields and assign values, with the last item in the array pop

I'm working with a div containing the id "inputs" in my HTML file, along with the following JavaScript code: let countries = [ {country: "Honduras", script: `<script src="crazy dog eats drool"> 'cha cha'` }, {country: "Chile", ...

Avoid triggering the API with rapid successive clicks

My project involves creating an Instagram-clone with like and dislike buttons. When a user is logged in and hasn't liked or disliked a post yet, both buttons appear as black. If the user likes a post, the like button turns blue, and if they click disl ...

My simple application is experiencing a problem where ComponentDidMount is not being invoked

I used a tool called create-react-app to build this simple application. Strangely, the ComponentDidMount method is never getting invoked. import React, { Component } from "react"; class App extends Component { componentDidMount() { console.log("M ...

Encountering issues with token header syntax while making an API call in Google Sheets using Apps Script

Uncertain about the correct syntax for the header bearer token section in this code snippet. ... // -------------------------------------------------------------------------------------------------- // // iTunes Music Discovery Application in Google Sheet ...

Vue and Vuex retrieve state data from the server in a single request

When loading the History view, data is fetched from the backend server using a Vuex action called in the created() lifecycle hook. This data is then passed to the history table through a computed function named history(), which accesses the history module ...

Unable to transfer an array from getStaticProps method in Next.js

Whenever I pass a JSON array from getStaticProps in Next.js, I encounter this specific error message when trying to access it. TypeError: Cannot read property 'contentBody' of undefined module.exports../pages/[author]/[article].js.__webpack_expo ...

Tips on narrowing down the type of callback event depending on the specific event name

I've been working on implementing an event emitter, and the code is pretty straightforward. Currently, tsc is flagging the event type in eventHandler as 'ErrorEvent' | 'MessageEvent'. This seems to be causing some confusion, and I ...

What is the best way to show and hide text by toggling a link instead of a button?

I need help with toggling between two different texts when a link is clicked. I know how to achieve this with a button in JQuery, but I'm not sure how to do it with a link. <h1>Queries and Responses</h1> <p>Query: What is the larges ...

How do useCases interact with each other within Clean Architecture principles in NodeJS?

I'm currently working on implementing Bob Martin's Clean Architecture in my project, and I have a question. How do use-cases interact with each other? For instance: In my project, there are entities for Department and Employee. The Department ...