Combine the common id field from two distinct arrays in AngularJS

I have two distinct arrays of data objects, each containing multiple fields: https://i.stack.imgur.com/tMM4l.png https://i.stack.imgur.com/ScgPh.png Here is an example of the data object array with the inclusion of the eventId field.

https://i.stack.imgur.com/21Vbv.png

The annotateData object also contains a eventId field that corresponds with those in the data object. I aim to identify which data element shares the same eventId as found in the annotateData, and then combine the respective annotateData element with the corresponding data object element. Consequently, the output will consist of a data object with augmented annotateObject fields.

data: [{
  0:{ annotateData fields + existing data fields} //if eventId matches
}]

Is there a more efficient approach to achieve this without iterating through the entire data object?

Answer №1

Utilizing a loop seems like the most effective approach for this task. However, incorporating some helper methods to simplify the process is beneficial. One such example can be found here:

Array.prototype.indexOfWithKeyValue = function(key, value) {
  var index = -1;
  var _this = this;

  for (var i = 0; i < this.length; i++) {
    var item = _this[i];
    if (item[key] === value) {
      index = i;
      break;
    }
  }

  return index;
};

Array.prototype.find = function(key, value) {
  var index = this.indexOfWithKeyValue(key, value);
  return this[index];
};

To further streamline the process:

var annotateData = [];  // example data
var data = [];  // example data

angular.forEach(annotateData, function(aData) {
    var matchingData = data.find("eventId", aData.eventId);

    if (matchingData) {
        // Merge relevant fields from "annotateData" into "data"
        angular.merge(matchingData, aData);
    }
});

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

performing an AJAX request to the controller method in a Rails application

I am currently facing an issue with making an ajax call to my controller class PatientRecordController < ApplicationController def export .... end end Within my javascript file, the code snippet is as follows: $(document).ready(function(){ ...

Implement a dispatcher in raw JavaScript using React combined with the Redux Toolkit package

In my React app, I have been using Redux and Redux Toolkit within React components by utilizing the useDispatch and useSelector hooks. However, I now need to update the Redux store from a pure JavaScript module that interacts with IndexedDB to save user da ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...

Can you explain the significance of the 'X-Bandwidth-Est 3' error message that states, "Refused to get unsafe header"?

I'm currently facing an issue with all the websites I am working on where I keep encountering the following error: Refused to get unsafe header "X-Bandwidth-Est 3" in base.js. This error seems to be related to a YouTube file named base.js, but after ...

JavaScript function not executing

Within a panel in an UpdatePanel, there is both a dropdown list and a file upload control. The goal is to enable the Upload button when a value is selected from the dropdown and a file is uploaded. This functionality is achieved through a JavaScript functi ...

Reactstrap and React-router v4 are failing to redirect when there is a partial change in the address link

Within the header of my website, <NavItem> <NavLink tag={Link} to="/template/editor">Create New Template</NavLink> </NavItem> On the routing page of my website, <BrowserRouter> <div className="container-fluid"> ...

Tips for keeping the hover effect of a sibling element in Material-UI

Card Component import image from "../../Assets/pic.jpg"; import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardActionAre ...

When conducting tests using Selenium and the headless Google Chrome browser in Java, the dynamic JS content fails to load

Currently, I am in the process of testing a website that I have developed as part of a Spring Boot project using Selenium. While I can successfully test basic functionalities such as page loading and title verification, I am encountering difficulties when ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...

Tips for showcasing the error message from the back-end instead of the status code

After setting up a Backend server and deploying it to Heroku, I have been using the server URL to send and receive data. However, I've encountered an issue where instead of displaying the actual error message, the status code is being returned. Here ...

parallelLimit asynchronously executes in limited quantities once

Utilizing async.parallelLimit to update database records in batches of 10 that total 1000 each time is my current challenge. I am exploring how to implement this feature in my code but have run into some issues. Despite studying example interpretations, my ...

What could be the reason for the jQuery not displaying JSON data in the console log?

When I put this code into a file named test.html: <html> <head> <title>Test</title> </head> <body> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"& ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...

Facing challenges in both client-side and server-side components

import axios from 'axios'; import Image from 'next/image'; export const fetchMetadata = async({params}) => { try { const result = await axios(api url); return { title: title, description: Description, } / } catch (error) { con ...

Using ng-repeater to create a ui-grid within ui-tabs

I have a simple user interface tab with a grid, but when I switch tabs, the page needs to be scrolled in order to see the table. <uib-tabset class="tab-container tabbable-line"> <uib-tab ng-repeat="user in vm.users" heading="{{user.user.fullN ...

Attempting to transfer information between components via a shared service

Currently, I am utilizing a service to transfer data between components. The code snippet for my component is as follows: constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) { } ngOnInit() { this.psSe ...

The scroll function within the inner div is malfunctioning on the Firefox browser

Scrolling within inner div is not functioning properly in the Mozilla Firefox browser. However, it works seamlessly in Chrome. Is there a workaround for enabling scrolling in Firefox? Here is the fiddle link: http://jsfiddle.net/t6jd25x9/2/ body { f ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

Using Javascript to iterate through an array of images can display a placeholder image as the previous or next image when the loop reaches the beginning or end of the array

//array of images const programmingLanguages = [jsIcon, htmlIcon, cssIcon, csharpIcon]; Functions for displaying next and previous images. function incrementLanguage() { if (languageIndex + 1 === programmingLanguages.length) { setlanguage ...

When I changed the encoding of a live texture to sRGB in Three.js, the frame rate dropped by fifty percent

I am currently working on a threejs application that requires updating a texture in each frame. The output encoding of the THREE.WebGLRenderer is set to sRGB. Upon setting the texture encoding to sRGB, I observed that the rendering result is accurate. How ...