Combining two array objects in JavaScript to create a single array object and iterating through each index or object

let objectArray1 = [{key1: 1}, {key2: 2}, {key3: 3}];

let objectArray2 = [{operator: LESS THAN}, {operator: GREATER THAN}, {operator: NOT EQUAL}];

In this scenario, the goal is to combine each object in objectArray2 with the corresponding object in objectArray1. For example, merge object at index 0 in objectArray2 into the object at index 0 in objectArray1 and so on.

//result = [{key1: 1, operator: LESS THAN}, {key2: 2, operator: GREATER THAN}];

During or after merging, it is required to iterate through each resulting object and create a new object with properties (field, input, operator) which are then pushed into an array.

field = key from objectArray1 (key1, key2, key3)
input = value from objectArray1 (1, 2, 3)
operator = "operator" from objectArray2

// let endResult = [{field: key1, input: 1, operator: LESS THAN}, {field: key2, input: 2, operator: GREATER THAN}];

Thank you!

Answer №1

It appears this code accomplishes your desired outcome by assuming familiarity with the data and bypassing error checks, simply merging them as requested.

const arrayOne = [{a:1},{b:2}, {c:3}];

const arrayTwo = [{operator: "LESS THAN"}, {operator:"GREATER THAN"}, {operator:"NOT EQUAL"}];

let finalResult = [];
let counter = 0;
let newObj = {};

arrayOne.forEach(function(fieldInput){
    for (field in fieldInput) {
        newObj.field = field;
        newObj.input = fieldInput[field];
        newObj.operator = arrayTwo[counter]['operator'];
        counter++;
        finalResult.push(newObj);
        newObj = {};
    };
})

// finalResult = [{field:a, input:1, operator: LESS THAN}, {field:b, input:2, operator: GREATER THAN}, {field:c, input:3, operator: NOT EQUAL}]

Answer №2

Breaking down this issue into two main steps will make it easier to tackle: 1) Combining objects 2) Processing the combined objects

A versatile function for merging can be written as follows:

if (!Object.prototype.combine) {

      Object.prototype.combine = function (object) {

        for (key in object) {

          if (typeof object[key] === 'object' && 
              typeof this[key]   === 'object' && 
              this.hasOwnProperty(key)) {

            this[key].combine(object[key]);      

          } else {      
            this[key] = object[key];      
          }

        }    

        return this;  
      };
};

The above code snippet establishes a method that is shared among all Objects. Its functionality is illustrated here:

var obj1 = { 'a': 7 },
    obj2 = { 'b': 2 };

obj1.combine(obj2);

console.log(obj1); // { 'a': 7, 'b': 2 };

In general practice, directly modifying Objects like with the .combine method may not be recommended, but creating a similar feature with a different API should be straightforward. For instance, one could design a function called extend (obj1, obj2) { carry out necessary operations.. and yield an extended object }

To address the merging aspect, utilizing a loop to traverse the merged object and populate an array with new objects is key. A basic implementation might resemble the following:

for (var prop in mergedObject) {
  var tempObject = {};
  if (prop === 'operator') {
    tempObject.operator = mergedObject.operator;
  } else {
    tempObject.field = prop;
    tempObject.input = tempObject[prop];
  }
  endResult.push(tempObject);
}

This guideline should assist you in resolving the merging and processing of objects efficiently.

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

What is the most efficient way to organize an array by date?

Here is the data I have: const data = [{date: "2022-05-10 13:36:00", open: 155.535, low: 155.4, high: 155.67, close: 155.44}, {date: "2022-05-10 13:35:00", open: 155.23, low: 155.2102, high: 155.62, close: 155.53}, {date: "2022-05 ...

Removing empty table rows using JavaScript when the page loads

Within my HTML table, I have noticed some empty cells and rows that need to be removed. To give an example of the code: <table id="7"> <tr> <td>Name</td> <td>Type</td> <td>Parent</td> <td>Time</td&g ...

Detecting the Presence of 5 Consecutive Numbers in an Array using JavaScript

I am struggling to find a way to identify if a sorted Array consists of 5 numbers in consecutive order. The catch here is that the Array can have duplicate and double-digit numbers mixed within it. I attempted to implement this logic but unfortunately, my ...

Issue with jQuery.off when using a dynamic function name

I am currently implementing a modular pattern for writing my JavaScript code and it has been an enjoyable experience! However, I have encountered a challenging situation. My Namespace structure looks like this: var settings, handlers, objects, Namespace ...

Encountering issue with 'mongodb-connection-string-url'

As a beginner, I am struggling to understand the error message. When I try to run the app.js file, I receive the following log message. I read that I need to upgrade my MongoDB, but since I am using Windows 7, this seems impossible. PS G:\AWebDev&bsol ...

Retrieving the total count of data entries from the JSON server endpoint

Working on a practice application with the JSON server serving as the backend, I have a question. Is there a way to determine the total number of records at an endpoint without actually loading all the records? For example, if my db.json file contains da ...

Comparing prevProps and this.props in React Native Redux: What is the most effective method?

Does anyone know how to efficiently handle triggering a function in my React Native app only when a specific prop has changed? This is the current implementation I have: componentDidUpdate(prevProps) { if (prevProps.a !== this.props.a) { <trigger ...

Encountering difficulties when attempting to load a module with the "js" extension in a TypeScript environment

When making a GET request with Systemjs, the extension .js is not being added to the URL. These are my TypeScript Classes customer.ts import {Address} from "./Address"; export class Customer { private _customerName: string = ""; public Customer ...

The CSS property overflow:hidden or overflow:scroll is not functioning as expected when applied to a

On my practice website, I have set up a demonstration for showcasing text data. The issue arises when the user inserts an excessive amount of characters in the text box. To address this, I would like the text to be scrollable so that all content can be d ...

Display a div using data from a Model in MVC

I am working with a model List that has fields ContainerId (div id) and Code (HTML code), which I am passing to a Razor View. Can you suggest the most effective way to display the code from the model in the containerId? My initial thought is to utilize j ...

Whenever I attempt to test the get all route, I encounter the error message "TypeError: Cannot read property '1' of null"

I'm currently working on developing a login system. When attempting to retrieve all users from my MySQL database in order to test the system, I encountered an error that reads: TypeError: Cannot read property '1' of null at firstchar (E: ...

Grabbing numerous selections from a dropdown menu

I am looking to extract multiple options from a dropdown menu and then send them via email. I have attempted the given code below: HTML: <select name="thelist[]" multiple="multiple"> <option value="Value 1">Value 1</option> <option v ...

The function update in chart.js is not available

I encountered an issue while trying to update my chart. When I clicked the button, an error message popped up saying TypeError: pieChartData.update is not a function const LatestSales = props => { const {pieChartData} = props; const toggle ...

Is there a way to make the directional light illuminate only one half of the sphere in Three js (R3F)?

I'm trying to achieve a lighting effect on a sphere using two directional lights. One light is positioned in front of the sphere to mimic sunlight, while the other is placed towards the back to represent city lights. I'm experimenting with differ ...

Tips for effectively updating Redux state in ReactJS reducer

I have a complex structure stored in my Redux data store that involves filterData and selectedFilters. Each filterId has an array of selectedFilters with specific filterName, text, and value properties. { filterData: { 22421: { fil ...

Incorporate 3 additional compound filters with shuffle.js

Is there a way to add a third compound filter to the existing shuffle.js code provided below? // ES7 will have Array.prototype.includes. function arrayIncludes(array, value) { return array.indexOf(value) !== -1; } // Convert an array-like object to a r ...

What is the best way to adjust a wide HTML table to make it narrow enough to fit perfectly within the screen width?

I need assistance with formatting an HTML table that contains multiple columns: <table id="req_header" border="2" style="overflow: auto;"> <tr> <th><i class="fa fa-solid fa-check"> ...

Perform a check on the state of the slideToggle using an if-else function and provide a report on the slideToggle state

http://jsfiddle.net/vmKVS/ I need some help understanding the functionality of slideToggle using a small example. After toggling for the first time, the options element changes color to green. However, I expected the menu element to turn red when I togg ...

Using PHP's json_encode function to convert to a JavaScript object may not be

I've encountered a PHP script that resembles this: $exec[0] = shell_exec("cat /etc/msm.conf | grep JAR_PATH"); $exec[1] = shell_exec("msm server list"); if(strstr($exec[1],'[ ACTIVE ] "mc-srv" is running. Everything is OK.') !== FALSE) ...

Prevent tracking of campaigns in Google Analytics by not following tagged links from banners to a website

My website is connected to Google Analytics. I have banners on my site that link to external pages with tracking tags added to the URL: However, I am not seeing campaign statistics in the Traffic Sources - Campaigns section of my Google Analytics account. ...