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

Javascript tree structures that enable the drag-and-drop of multiple items

At the moment, our application utilizes the ExtJS tree view. We now have a need for users to be able to select multiple nodes (which the tree view already supports through a pluggable selection model) and then drag these selections to another section of th ...

When using props.onChange(e.target.value) in a textField component in Material UI, it unexpectedly returns an object instead of a value

function FormInput(props) { const classes = formInputStyles(); return ( <div> <TextField onChange={(e) => props.onChange(e.target.value)} InputProps={{ classes, disableUnderline: true }} {...pro ...

Angular: Choose the label of the currently selected option

I am working with a form that has a select menu displaying options using AngularJS: <form name="myForm" <select ng-model="myModel" ng-options="..."> </form> The output of the select menu looks like this: <select> <option valu ...

Storing HTML values in a Meteor database is a common practice for web

Within my meteor project, I have a paragraph in HTML containing a JSON value as follows: {"Active Template Id":"6467","Shirt Brand":"levis","ProductId":"EB301","Brand":"on","Material":"cotton","Price":"1800","Combo Id":"S90"} I am looking to store this v ...

The useEffect function is failing to execute, leading to an issue with an undefined variable

Attempting to retrieve a specific string with the help of useRouter, then utilizing that same string to access a particular document from Firebase is my current goal. This sequence of actions is supposed to take place within the confines of the useEffect f ...

Nuxt and Express server are unable to receive API requests when in production mode and the /dist directory

My Nuxt app is running smoothly on my local server, with all API requests working perfectly using the serverMiddleware property in nuxt.config.js. However, when I run yarn generate, the path to the API server gets lost and no data is loaded. Here are some ...

Unable to display bar chart on PHP webpage showing database number volumes using JavaScript

I'm currently working on generating a bar chart to show the number of bookings per month. I have two separate SQL queries that retrieve the data correctly, as confirmed by testing. However, when I try to run the file in my browser, nothing is displaye ...

Incorporate the key as a prop within a Child Component in a React application

I am trying to display a list of elements in React, where the key of each element is used as an index in front of the item. However, when I try to access props.key, it just returns undefined. Does anyone have any suggestions on how to access the key proper ...

String casting for large JavaScript integers may require rounding to function properly

When trying to pass a large integer to a function from an onclick event in HTML, I always encounter issues with rounding. Despite using bigInt libraries, I still struggle to pass the full number accurately and would prefer a simple string casting method. ...

Altering the appearance of an input field upon submission

https://jsfiddle.net/3vz45os8/7/ I'm working on a JSFiddle where I am trying to change the background color of input text based on whether the word is typed correctly or incorrectly. Currently, it's not functioning as expected and there are no e ...

Using $.getJSON is not functioning properly, but including the JSON object directly within the script is effective

I'm currently working on dynamically creating a simple select element where an object's property serves as the option, based on specific constraints. Everything is functioning properly when my JSON data is part of the script. FIDDLE The follow ...

Server Error: Reactjs doesn't support posting images

I am experiencing an issue in my ReactJS project. When I attempt to upload an image using react-images-uploader, I encounter the following error: "Cannot POST /images error" Below is the code snippet for the image upload: <ImagesUploader ur ...

Getting elements in order with bootstrap

Can you help me align the "Format Example" string with the textual labels of the input fields without using static width in AngularJS with Bootstrap? The current alignment is right-justified but I would like it to be more dynamic as shown in the screenshot ...

AJAX seems to be struggling to recognize JSON data as JSON format

I am facing an issue with my AJAX call where the data received from the server is not being treated as JSON, despite setting the datatype to json: function RetrieveMateriasFromServer(callback){ var status_aux; //HTTP request for data from the given UR ...

Tips for assigning information from a react hook within a function or event

Currently, I am in the process of learning how to create hooks in order to efficiently reuse data that needs to be modified across different components. For my project, I am utilizing Material UI's Tabs and require the use of a custom hook called use ...

The 'ObjectID' property is not present in the 'CollectionStatic' data type

Encountering an issue with the MongoDB npm module: mongoId = new Mongo.Collection.ObjectID()._str; Attached is a screenshot for reference. Appreciate any assistance. ...

Incorporate a fresh key-value pair into the Redux Toolkit's state

I am currently working on an application that enables users to create and modify recipes. To manage the state, I have chosen to utilize React Toolkit and Redux. Here is an example of the state structure: const ingredients = [ { ingredientName: &apos ...

Creating a series of images in JavaScript using a for loop

Currently attempting to create an array of images, but with a large number of images I am looking into using a "for loop" for generation. Here is my current code snippet : var images = [ "/images/image0000.png", "/images/image0005.png", "/ima ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...