What is the best way to combine an additional array into a different project attribute?

There are 2 arrays being used.

This is the content of userGroups: console.log(this.items)

[
    {
        "id": 63,
        "name": "URLGROUP-1643836551908"
    }
]

The contents of urls are shown below:

userGroup can contain URLs

[
    [
        {
            "id": 110,
            "group_id": 63,
            "url": "https://www.apple.com",
            "url_num": 1,
            "max_iteration": 2
        },
        {
            "id": 111,
            "group_id": 63,
            "url": "https://www.google.com",
            "url_num": 2,
            "max_iteration": 2
        }

    ]
]

The goal is to combine them in the following way: id, name, url

[
    {
        "id": 63,
        "name": "URLGROUP-1643836551908",
        "url": [
        {
            "id": 110,
            "group_id": 63,
            "url": "https://www.apple.com",
            "url_num": 1,
            "max_iteration": 2
        },
        {
            "id": 111,
            "group_id": 63,
            "url": "https://www.google.com",
            "url_num": 2,
            "max_iteration": 2
        }

    ]
    }
]

Attempts to merge them have been unsuccessful so far. Performing nested loops could impact performance negatively.

What would be the best approach in this situation?

If I implement the following code snippet:

for (let i = 0; i < this.items.length; i++) {
    for (let j = 0; j < urls.length; j++) {
        if (i == j) {
            this.items[i].urls = urls[j]
        }
    }
}

Here is how the updated items look like after executing the above code:

[
    {
        "id": 63,
        "name": "URLGROUP-1643836551908",
        "details": [
            {
                "id": 110,
                "group_id": 63,
                "url": "https://www.acme.com",
                "url_num": 1,
                "max_iteration": 2
            }
        ]
    }
]

Answer №1

While the example may not have a lot of variety, I will make an assumption that the second array (of arrays) organizes items with matching group_id values into the same subarray.

One approach could be to create a Map using the first instance of each group_id from the subarrays and link each one to its respective subarray.

The next step would involve mapping the first array to objects enriched with a url property fetched from the Map, based on each object's id property:

let userGroups = [{"id": 63,"name": "URLGROUP-1643836551908"}];

let urls = [[{"id": 110,"group_id": 63,"url": "https://www.apple.com","url_num": 1,"max_iteration": 2},{"id": 111,"group_id": 63,"url": "https://www.google.com","url_num": 2,"max_iteration": 2}]];

let urlsMap = new Map(urls.map(arr => [arr[0].group_id, arr]));
let result = userGroups.map(obj => ({...obj, url: urlsMap.get(obj.id)}));

console.log(result);

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

Is it possible to retrieve server data in a JavaScript file?

EDIT: I accidentally omitted a piece of relevant code I am looking to access the "jsonData" value from my server in my JavaScript file. Can someone guide me on how to retrieve these values? Here is the server-side code: var express = require('expre ...

Guide to utilizing Reduce for obtaining a fresh Array of Objects in Javascript

I am a beginner in coding, so I apologize if this question seems basic. I am working with an array that contains different types of pies along with their prices: pieArr = [blueberry, strawberry, pumpkin, apple] My goal is to create an array of objects re ...

What could be the reason for StaticComponent constantly re-rendering despite having a static state that does not change

I'm trying to grasp the core concepts of how React triggers component re-rendering upon state changes. In the scenario described below, the console.log('hi') statement within the StaticComponent is executed every time the onChange event han ...

The jQuery click function triggers immediately upon the loading of the page

Despite my best efforts to resolve this issue independently and conduct extensive research on Google, I am still unable to identify the root of the problem. It seems that the click function continues to activate upon page load. Kindly elucidate the under ...

What is the process for obtaining the public email address of a Facebook Business Page through the Graph API?

At the moment, I am utilizing the Graph API and the PHP SDK from Facebook to collect data and recent wall posts from a Business Page. This information includes details like name, address, and phone number. However, even though the public email address is ...

Exploring the interactive doughnut graph using SVG and Vue.js

Looking to create a unique dynamic donut chart using SVG and Vue. I want it to mirror the exact SVG format found on this webpage: (To see the animated chart, select a dish and click on ingredients) This might not have been the best approach, but it was ...

Exploring Swift 3 capabilities: effortlessly showcase the JSON data stored within arrays

Facing a challenge while dealing with JSON data in Swift3. I have managed to retrieve all the data except for the street key-value pair which should be considered as an array or dictionary. Struggling to understand how to extract the data for this particu ...

Utilizing C in WebAssembly to return string values

Is it possible to retrieve a JavaScript string from a WebAssembly function? https://dev.to/azure/passing-strings-from-c-to-javascript-in-web-assembly-1p01 - not functional C #include <stdio.h> #include <string.h> void jsPrintString(const ch ...

Exploring the capabilities of VueJs in detecting events triggered by parent components

When users click on a specific image in the Collection(parent component), my goal is to display that image in a Modal(child component). Below is the code snippet: routes.js import Home from './components/Home'; import About from './compone ...

Day Change Triggers React [Native] View Update

I've been working on a React Native component that needs to update itself when the day changes, regardless of user interaction. Is there another method besides using setInterval for this task? If I use setTimeout in my viewDidLoad function with the n ...

Is it possible to set up a universal type definition in TypeScript version 2 and above?

I have a collection of straightforward .ts files, not part of any projects but standalone .ts scripts. They implement certain node.js features. Both TypeScript and node type definitions are set up through the following commands: npm install -g typescript ...

What is the best way to use VBA to fetch and import JSON data from a URL?

Here is a JSON array that can be accessed at the following URL: This is the output of the JSON array: {"-0p":{"date":"2015-01-01","string":"apple","value":1},"-1p":{"date":"2015-02-04","string":"banana","value":50},"-2p":{"date":"2015-02-03","string":"c ...

Converting a JavaScript hash into a single object: A step-by-step guide

I have an array of objects in the following format: var log=[ { billkey:"Name", billvalue:"ABC" }, { billkey:"Department", billvalue:"Computer" }]; and I want to convert it into a single object like this: var log={ "Name":"ABC", " ...

Sails JS - Flash message display issue on Heroku in production environment, works smoothly in development mode

I'm experiencing an issue with the flash message on my local machine during development, as it works fine there but not when I deploy the app on Heroku. I've been searching for a solution without any luck so far. api/policies/flash.js module.ex ...

Find the value of the nearest input field using jQuery

I'm working with HTML code that looks like this: <tr> <td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td> < ...

How can I update the value of a span element that was added to the HTML document through an AJAX request?

When a modal is triggered on click, data is added to it through an AJAX request to a PHP file. After the AJAX call, I want the values in span elements within the modal to change simultaneously with the input field of the modal. I attempted this JavaScript ...

Tips for avoiding automatic updates to .js scripts after pressing F5

Is there a method to stop a JavaScript script from resetting when the user refreshes the page? For instance, if I have a picture slider that is constantly changing images, I would like the script to continue where it left off instead of starting over wit ...

Unable to modify the chosen option within a select dropdown

I am trying to change the selected option of a select element using jQuery, but I can't seem to make it work. Here is the code I have: $("#ID option[value=grpValue]").prop('selected', 'selected').change(); If I manually type in a ...

Trouble locating DOM element in Angular's ngAfterViewInit()

Currently, I am attempting to target a specific menu item element within my navigation that has an active class applied to it. This is in order to implement some customized animations. export class NavComponent implements AfterViewInit { @ViewChild(&a ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...