Using Javascript to map an array with objects from a different array and then returning the computed array

I'm struggling to solve a seemingly simple issue. I have an array that looks like this:

Array 1:
[
    {
        "id": 1,
        "date": "2019-03-27",
        "time": 1,
        "max_tasks": 3,
        "reservations": [
            5,
            2
        ]
    },
    ...
]

Within the reservations property of Array 1, there are IDs that correspond to another array shown below:

Array 2:
[
    {
        "id": 5,
        "app": 1,
        "comment": "test 5"
    },
    ...
]

Expected Outcome:

I need to merge the data from Array 2 into Array 1 based on matching IDs in both arrays. The desired result is to return Array 1 with the objects added from Array 2.

I am using Vue.js and would like to achieve this through computed properties or getters in order to directly access the updated array in my component. Any alternative methods to accomplish this task are welcome.

This is the output format I aim to achieve:

[
    {
      'id': 1,
      'date': '2019-03-27',
      'time': 1,
      'max_tasks': 3,
      'reservations': [
        {
          'id': 5,
          'app': 1,
          'comment': 'test 5'
        },
        ...
      ]
    },
    ...
]

Thank you for your assistance.

Answer №1

While it may not be the most optimal solution, why not give this code a test run?

let arr1 = [{
    "id": 1,
    "date": "2019-03-27",
    "time": 1,
    "max_tasks": 3,
    "reservations": [
      5,
      2
    ]
  },
  {
    "id": 2,
    "date": "2019-03-28",
    "time": 1,
    "max_tasks": 3,
    "reservations": []
  },
  {
    "id": 3,
    "date": "2019-03-29",
    "time": 1,
    "max_tasks": 3,
    "reservations": []
  },
  {
    "id": 4,
    "date": "2019-03-30",
    "time": 1,
    "max_tasks": 3,
    "reservations": []
  },
  {
    "id": 5,
    "date": "2019-03-31",
    "time": 1,
    "max_tasks": 3,
    "reservations": []
  },
  {
    "id": 6,
    "date": "2019-04-01",
    "time": 1,
    "max_tasks": 3,
    "reservations": []
  },
  {
    "id": 7,
    "date": "2019-04-02",
    "time": 1,
    "max_tasks": 3,
    "reservations": [
      3
    ]
  }

]
let arr2 = [{
    "id": 5,
    "app": 1,
    "comment": "test 5"
  },
  {
    "id": 2,
    "app": 1,
    "comment": "test 2"
  }
]
arr1.forEach(o => {
  let updatedReverations = []
  o.reservations.forEach(r => {
    updatedReverations.push(arr2.filter(a2 => r === a2.id)[0] || r)
  })
  o.reservations = updatedReverations
})
console.log(arr1)

Answer №2

maybe this will do the trick

var arrayOne = [
    {
        "id": 1,
        "date": "2019-03-27",
        "time": 1,
        "max_tasks": 3,
        "reservations": [
            5,
            2
        ]
    },
    {
        "id": 2,
        "date": "2019-03-28",
        "time": 1,
        "max_tasks": 3,
        "reservations": []
    },
    {
        "id": 3,
        "date": "2019-03-29",
        "time": 1,
        "max_tasks": 3,
        "reservations": []
    },
    {
        "id": 4,
        "date": "2019-03-30",
        "time": 1,
        "max_tasks": 3,
        "reservations": []
    },
    {
        "id": 5,
        "date": "2019-03-31",
        "time": 1,
        "max_tasks": 3,
        "reservations": []
    },
    {
        "id": 6,
        "date": "2019-04-01",
        "time": 1,
        "max_tasks": 3,
        "reservations": []
    },
    {
        "id": 7,
        "date": "2019-04-02",
        "time": 1,
        "max_tasks": 3,
        "reservations": [
            3
        ]
    }

]

var arrayTwo = [
    {
        "id": 5,
        "app": 1,
        "comment": "test 5"
    },
    {
        "id": 2,
        "app": 1,
        "comment": "test 2"
    }
]

for (var index = 0; index != arrayOne.length; ++index) {
    arrayOne[index].reservations = arrayOne[index].reservations.map(id => {
        var reservation = arrayTwo.find(reservation => reservation.id == id)
        return reservation || id;
    });
}

This code snippet attempts to locate a reservation in array 2 and if it's not found, it won't replace the ID.

Answer №3

Use this function to get a fresh copy of the merged array.

function createMergedArray(originalArr, mergeArr){
return originalArr.map(element=>{
    if(element.items.length>0){
     let newItems = element.items.map(itemId=>{
            let foundItem = mergeArr.find(item=>{
                return item.id === itemId
        })
        if(foundItem){
            return foundItem;
        }
        else{
            return itemId;
        }
     })
     element.items = newItems;
  }

  return element;
});

}

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

The Parse.com cloudcode refuses to enter the success or error state

Running this code in my Parse cloud, I noticed that when I call it from my app, it never enters the success or error statement. Could it be because the .save method isn't working? Any assistance would be greatly appreciated :) This is how I invoke t ...

I'm encountering difficulties in automatically populating the category field from an API

Hey there! I have set up a signup form and I am trying to automatically fetch categories from the server API to populate an input area. Everything seems to be in place, but for some reason, I am unable to retrieve the data. API: Here is the code I'm ...

Combine two or more Firebase Observables

Currently, I am working on creating an Observable using FirebaseObjectObservable. However, before I can accomplish this, I need to query a Firebase list to obtain the key IDs required for the FirebaseObjectObservable. The structure of my data is as follow ...

Display the element only when the request sent with getJSON exceeds a certain threshold of time in milliseconds

Here's a snippet of my JavaScript code: surveyBusy.show(); $.getJSON(apiUrl + '/' + id) .done(function (data) { ... surveyBusy.hide(); }) .fail(function (jqXHR, textStatus, err) { ... surveyBusy. ...

Ways to refresh the main frame

Here is an example of parent code: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Parent</title> </head> <body> <iframe src="https://dl.dropboxusercontent.com/u/4017788/Labs/child.html" width ...

The necessary data is missing in the scope of the callback function

I'm facing an issue with a callback function's variable losing its scope. Consider the following simplified array of two objects: const search = [{socket: new WebSocket('ws://live.trade/123')}, {socket: new WebSocket( ...

Are you searching for the origin of a dynamic dropdown widget or database?

Currently, I am browsing through and I have a query regarding accessing all available classes/options for the courses in a semester. There is a class locator on the top left of the page with a dynamic drop-down menu. Can anyone suggest how I can access ...

Is there a way to determine whether all fields in a schema have been populated or remain empty?

I am working with a schema that looks like this: How can I determine if all the fields in the schema have been filled or not? The front-end (React.js) includes an onboarding process where users who are logging in for the first time need to complete onboa ...

Transferring data from a React file to a plain HTML page

What is the best way to transfer information from a React app to a static HTML file? For instance, if I collect data through a form in a React app.js file, how can I then send that data to a basic HTML file? ...

What is the best way to navigate back to the top of the page once a link has been clicked?

One issue I'm facing is that whenever I click on a link in NextJS, it directs me to the middle of the page: <Link href={`/products/${id}`} key={id}> <a> {/* other components */} </a> </Link> I believe the problem l ...

Restricting the number of lines within a paragraph in Angular 2

Is there a method to limit the number of lines in a <p> tag and add an ellipsis (...) at the end? Using character count for truncation doesn't work well as the width of the element varies according to device screen size. ...

What is the method to process a JSON path containing a special character like "@"?

I'm attempting to retrieve JSON data from an API with the following structure. My current approach involves using JavaScript. The code snippet I have utilized is displayed below. <p>"stations": [</p> <p id="data"></p> ...

Utilize ViewChild to handle changing elements in Angular 2 and Ionic 2 applications

I am facing an issue where I want to dynamically add multiple IonicSlides, but I am unable to use @viewChild. Can anyone suggest a solution for this problem? Template.html : <div *ngFor="let name of title;let i = index;"> <ion-slide ...

Conceal an element from view upon clicking on it

Task at Hand : Implement a smooth element hiding effect upon clicking, similar to the behavior on this website , where the letter A fades away smoothly when clicked. Is it possible to achieve this effect using only HTML, CSS, and JavaScript? var t ...

Event not tracking properly due to missing label in GA event firing

Seeking assistance with a project I'm currently engaged in. I have created an HTML5 video containing a playlist and encountering difficulties setting up multiple labels in GA to track each individual video play. While I found code online, adapting it ...

What is the method to turn off readonly property for input fields in Laravel?

I'm encountering an issue with my Laravel project. I have a form with an input field that has the readonly attribute set. <input type="text" name="anamFam" id="anamFam" value="{{$aFam->anam_cont}}" readonly> When I click the edit button, I ...

Node.js server crashes upon automatic startup but remains stable when started manually

Currently, I am using Node.js and Socket.io to power an online chat feature. To manage the server, I have created a configuration file located at: /etc/init/example.conf The contents of this file are as follows: start on startup exec forever start /var/ ...

Swap out a term in a sentence with an interactive span element in real-time

I'm struggling with a seemingly simple task, and I feel quite embarrassed that I can't seem to solve it. My goal is to identify words in a string that begin with '@' or '#' and change their color to blue. The string itself com ...

"Encountering a problem with numerous callbacks in the getJSON method

I am working on creating marker pop ups that display information from different ajax requests on a map. In order to make the second call, I utilize an userID obtained from the first call. While the information from the second call is displayed correctly, ...

Accessing results from geocoder.geocode is restricted to local variables only

I need to extract longitude and latitude coordinates from google.maps.GeocodeResults in order to store them in an external Array<any>. Currently, I am able to display results[0], but encounter an OVER_QUERY_LIMIT error when attempting to add it to t ...