Creating a new array by combining data from two arrays: a step-by-step guide

Here is an array I have:

response=[
    {            
        "mId": "4a993417-3dae-4a85-bb2e-c535d7fda6d7",
        "title": "test2",
        "score": "4",
        "id": "91ce873f-6e58-4c30-86d4-4eb7f200640e"
    }
]
[
    {            
        "mId": "7896548-3dae-4a85-bb2e-c855d7fda6d7",
        "title": "discussion",           
        "score": "18",        
        "id": "91ce873f-6e58-4c30-86d4-4eb7f200640e"
    }
]
[
    {           
        "mId": "20d78952-3dae-4a85-bb2e-c535d7fda6d7",
        "title": "test",         
        "score": "1",          
         "id": "7777777f-6e58-4c30-86d4-4eb7f200640e"
    }
]

Next, I have this array:

mixture=[{"id":"4a993417-3dae-4a85-bb2e-c535d7fda6d7","name":"flour","description":"10g sold"}]
[{"id":"20d78952-3dae-4a85-bb2e-c535d7fda6d7","name":"teabag","description":"stock arriving"}]

I'm trying to match the mId from the response array with the corresponding array in mixture to find the name. Here's how the new array should look:

newArray=[{
"name":"flour"
"mId": "4a993417-3dae-4a85-bb2e-c535d7fda6d7",
            "title": "test2",
            "score": "4",
            "id": "91ce873f-6e58-4c30-86d4-4eb7f200640e"
}]
[{ "name":"flour"
           "mId": "4a993417-3dae-4a85-bb2e-c535d7fda6d7",
            "title": "discussion",           
            "score": "18",        
            "id": "91ce873f-6e58-4c30-86d4-4eb7f200640e"
}]
[{         "name":"teabag"
           "mId": "7896548-3dae-4a85-bb2e-c855d7fda6d7",
            "title": "test",           
            "score": "1",        
            "id": "7777777f-6e58-4c30-86d4-4eb7f200640e"
}]

Answer №1

To achieve the desired outcome, ensure that your response and blend arrays are accurately coded. Utilize both Array.prototype.map() and Array.prototype.find() in combination.

const modifiedArray = response.map(item => {
    const mix = mixture.find(mixtureItem => mixtureItem.id === item.mId);
    if (mix) {
        item.name = mix.name;
    }
    return item;
})

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

Issue with moving files after successful upload - encountering ENOENT Error

I am encountering a frustrating issue while trying to transfer files from the temp directory to the profile_pictures directory. This seemingly straightforward task has proven to be quite challenging as I have been stuck on it for an hour! The process shou ...

A Guide to Triggering a Method Upon Component Change in Angular

When working with Angular, Components have an ngOnInit() method. I am looking for the opposite of this method. Is there a method that gets called when the component is closed? Is there a way to detect in the TypeScript file if the component is being clo ...

Error: The module parsing process failed due to the presence of an octal literal in strict mode. To resolve this issue,

I'm currently attempting to incorporate the following regular expression into Angular6: const regexp = new RegExp('^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\\2))(? ...

How can I convert the >= value into an ASCII character within a TypeScript file?

Within my Angular TS file, I am attempting to identify if a string contains the characters >= and then substitute them with the corresponding ASCII character for greater than or equal to. Here is my current code snippet: @Input() public set textLabel(va ...

having trouble getting the jquery tooltipster plugin to function properly

As someone new to jQuery, I have a question that relates more to JavaScript than jQuery. Any assistance would be greatly appreciated. I've been using the Tooltipster Plugin to create tooltips when hovering over <td> elements in a data table. I ...

redux-saga 'call' effect fails to properly type saga parameters

My saga is defined as follows: type GenericFunction = (...args: any[]) => any; interface IFetchSaga<T extends GenericFunction> { saga: T, args: Parameters<T> } function* triggerChange<T extends GenericFunction>(fetchSaga: IFetchS ...

The function of cookieParser() is causing confusion

Having an issue that I've been searching for answers to without success. When using app.use(express.cookieParser('Secret'));, how can we ensure that the 'Secret' is truly kept secret? I'm feeling a bit lost on this topic. Is ...

When using the mui joy library, obtaining the input value upon submission may result in the retrieval of an "unidentified" response

Struggling to fetch user input for 2FA authentication using the mui JoyUI library. Attempted using e.target and searching for input value with no success. Clearly missing something in the documentation. Also gave 'useRef' a shot, but the code sni ...

displaying a confirmation using jQuery in CodeIgniter

Hello everyone, I am a beginner in CodeIgniter and I am seeking assistance. I am attempting to create a confirmation message (div id="delmsg") using jQuery when deleting a record from MySQL database. The delete operation is functioning properly, but the me ...

Avoid causing the newline character to display

var i = 'Hello \n World' console.log(i) /* Output: Hello World */ /* Desired output: Hello \n world */ var j = 'javscr\u0012ipt' console.log(j) /* Output: javscr ipt */ /* Desired output: javscr\u0012ipt */ ...

Swapping out the entire vue.js container

I have a custom vue.js widget that I initialize like so: var myWidget = new Vue({ el: '#widget-container', methods: { loadData:function() { // custom functionality here } }, }); The HTML structure is as f ...

The date conversion within AngularJS's interpolation is resulting in an incorrect timestamp

Given a timestamp of 1519347000, I am trying to convert it into a date format using interpolation like so: {{$ctrl.myTimestamp | date:'MMM d y, hh:mm'}} The resulting value is Jan 18 1970, 04:02, which is incorrect. The correct date should be F ...

What is the most effective way to redirect users accessing from Android devices?

Attempting to send all Android users to a designated page. I attempted this method using php, but uncertain of its reliability. Need assurance that it will work for all possible Android devices. Thoughts on the safety of this approach? <?php $user_ag ...

The key to subscribing only once to an element from AsyncSubject in the consumer pattern

When working with rxjs5, I encountered a situation where I needed to subscribe to an AsyncSubject multiple times, but only one subscriber should be able to receive the next() event. Any additional subscribers (if still active) should automatically receive ...

Attempting to incorporate a variable into the URL while making an Ajax POST request using jQuery

Currently, I am attempting to create a post using jQuery.ajax instead of an html form. Below is the code I am using: $.ajax({ type: 'POST', // GET is also an option if preferred url: '/groups/dissolve/$org_ID', data: data, success: fu ...

SVG tags are not functioning properly

Hello, I am new to working with SVG files. I have a set of icons created using SVG and I am attempting to use the <use> tag in order to display a specific part of an SVG file. However, I seem to be encountering some issues and I am unable to identi ...

What is the process for customizing or modifying the content of this TextField

My Material UI text field is filled with data from a nested JSON object retrieved from an API. Data can be shown in a TextField, Date Picker, or Select box depending on the FieldType value. The data appears correctly in the inputs, but it cannot be edite ...

Implementing Authorization token management with Axios in a Node.js environment

Looking to incorporate axios into my API tests. In order to set up the client, I need to first establish an authentication token, which I hope to retrieve using axios as well. What is the best way to retrieve it from asynchronous code? const axios = req ...

Guide on sending a request to an API and displaying the retrieved information within the same Express application

I recently developed a basic express app with API and JWT authentication. I am now attempting to enhance the app by incorporating page rendering through my existing /api/.. routes. However, I am facing challenges in this process. app.use('/', en ...

Oops! The program encountered an issue where it was unable to access the properties of an undefined variable, specifically while trying to

When creating a custom validation function in Angular, I encountered an issue where using a variable within the validation would result in an error: "ERROR TypeError: Cannot read properties of undefined (reading 'file')". This occurred when chang ...