Combining two arrays of objects in JavaScript to create a new array, using the properties of the objects

I am facing an issue with handling two arrays of JSON objects in JavaScript. I am trying to create a new array by mapping on the "Word_No" property of both arrays. Here is an example of how the arrays look like:

wordInfo (total length: 4000):


    [
    {
        "Word_No": "0",
        "Alarm_Bit": "0",
        "Alarm_No": "1",
        "Alarm_Description": "Alarm text 1"
    },
    {
        "Word_No": "0",
        "Alarm_Bit": "1",
        "Alarm_No": "2",
        "Alarm_Description": "Alarm text 2"
    },
    {
        "Word_No": "0",
        "Alarm_Bit": "2",
        "Alarm_No": "3",
        "Alarm_Description": "Alarm text 3"
    }
]

and wordTags (total length: 250):


    [
    {
        "Word_No": "0",
        "OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm0_15"
    },
    {
        "Word_No": "1",
        "OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm16_31"
    },
    {
        "Word_No": "2",
        "OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm32_47"
    }
]

I am trying to create a new array named Alarmlist (total length: 4000) with the following structure:


    [
    {
        "OPC Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm0_15",
        "Alarm_Bit": "0",
        "Alarm_No": "1",
        "Alarm_Description": "Alarm text 1"
    },
    {
        "OPC Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm0_15",
        "Alarm_Bit": "1",
        "Alarm_No": "2",
        "Alarm_Description": "Alarm text 2"
    },
    {
        "OPC Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm0_15",
        "Alarm_Bit": "2",
        "Alarm_No": "3",
        "Alarm_Description": "Alarm text 3"
    }
]

My current code using nested loops and mapping on the "Word_No" property is crashing due to the large size of the arrays. When I limit the iteration to a small number, the function works fine. I need a more efficient way to handle this problem. Any suggestions are appreciated.

Answer №1

To enhance efficiency and avoid redundant iterations, my suggestion is to start by creating a lookup object for OPC_Tag by utilizing Array.reduce() on wordTags. This approach will optimize performance and eliminate the need for a .find() operation during each iteration of the loop on wordInfo.

Subsequently, we can employ Array.map() on wordInfo to generate the desired end result:

let wordInfo = [ { "Word_No": "0", "Alarm_Bit": "0", "Alarm_No": "1", "Alarm_Description": "Alarm text 1" }, { "Word_No": "0", "Alarm_Bit": "1", "Alarm_No": "2", "Alarm_Description": "Alarm text 2" }, { "Word_No": "0", "Alarm_Bit": "2", "Alarm_No": "3", "Alarm_Description": "Alarm text 3" } ]
let wordTags = [ { "Word_No": "0", "OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm0_15" }, { "Word_No": "1", "OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm16_31" }, { "Word_No": "2", "OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm32_47" } ] 

// Create a lookup, mapping Word_No to OPC_Tag
let wordTagsLookup = wordTags.reduce((acc, { Word_No, OPC_Tag }) => { 
    acc[Word_No] = OPC_Tag;
    return acc;
}, {})

let result = wordInfo.map(({ Word_No, Alarm_Bit, Alarm_No, Alarm_Description}) => { 
    return { Alarm_Bit, Alarm_No, Alarm_Description, OPC_Tag: wordTagsLookup[Word_No] };
})

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

Answer №2

To optimize the process, I recommend creating a Map for the second array, using Word_No as the key. This way, you can easily map the array to objects with the translations derived from the Map. By utilizing object destructuring, the implementation can be concise and elegant:

// Example input data
const wordInfo = [{"Word_No": "0","Alarm_Bit": "0","Alarm_No": "1","Alarm_Description": "Alarm text 1"},{"Word_No": "0","Alarm_Bit": "1","Alarm_No": "2","Alarm_Description": "Alarm text 2"},{"Word_No": "0","Alarm_Bit": "2","Alarm_No": "3","Alarm_Description": "Alarm text 3"}];
const wordTags = [{"Word_No": "0","OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm0_15"},{"Word_No": "1","OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm16_31"},{"Word_No": "2","OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm32_47"}];

// Create a map using Word_No as the key:
const map = new Map(wordTags.map(({Word_No, OPC_Tag}) => ([Word_No, OPC_Tag])));
// Translate the data from source to target
const alarmList = wordInfo.map(({Word_No, ...rest}) => 
    ({OPC_Tag: map.get(Word_No), ...rest})
); 
console.log(alarmList);

Answer №3

To achieve this, you can utilize the .map() and .filter() methods in the following manner:

const wordInfo = [
  {
      "Word_No": "0",
      "Alarm_Bit": "0",
      "Alarm_No": "1",
      "Alarm_Description": "Alarm text 1"
  },
  {
      "Word_No": "0",
      "Alarm_Bit": "1",
      "Alarm_No": "2",
      "Alarm_Description": "Alarm text 2"
  },
  {
      "Word_No": "0",
      "Alarm_Bit": "2",
      "Alarm_No": "3",
      "Alarm_Description": "Alarm text 3"
  },
];

const wordTags = [
    {
        "Word_No": "0",
        "OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm0_15"
    },
    {
        "Word_No": "1",
        "OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm16_31"
    },
    {
        "Word_No": "2",
        "OPC_Tag": "HH.Application.TmpHmi_Var.TmpHmiC7.Alarm32_47"
    }
];

const data = wordInfo.map((wordInfoItem) => {
  const wordTag = wordTags
    .filter((wordTagItem) => (wordInfoItem["Word_No"] === wordTagItem["Word_No"]))[0];
  
  const updatedArray = {
    ...wordTag,
    ...wordInfoItem,
  };

  delete updatedArray['Word_No'];
  return updatedArray;
});

console.log(data);

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

The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input : @Input() usersInput: Section[]; export interface Section { displayName: string; userId: number; title: number; } Here is the Value List : 0: displayName: "بدون نام" ...

HTML and JavaScript code to desaturate or grayscale image rollovers without the need for additional image duplicates or sprites

Is there a way to achieve grayscale to color image rollover effects without duplicating images or using sprites? I'm looking for an alternative technique that can accomplish this. Any suggestions on how to implement it? ...

Pattern matching algorithm designed to eliminate background-color attributes

Looking to strip out any "background-color:[whatever];" styles from the text within a div. The plan is to eliminate all inline background-color styles completely. I've been eyeing JavaScript's string.replace(regex,str) as a potential solution ...

Is it possible to extract tooltip text from a website using Python and Selenium, specifically when the text is generated by JavaScript?

Can anyone help me retrieve the tooltip text that appears when I hover over the time indicating how long ago a game was played? You can find my summoner profile here. I have noticed that the tooltip text is not visible in the HTML code and suspect it may ...

Looping through AJAX calls

Currently, I have a dataset that needs to be displayed on my webpage. Each item in the list has a unique identifier. Every item represents a bar and there is a corresponding document for bars that are visited by at least one user. If a bar has no visitors ...

Activate a function when the VueJS countdown timer hits zero

I've successfully created a countdown timer in the template that decrements a number perfectly. Now, I'm facing the challenge of triggering a function declared within the methods section once the countdown reaches 0. Despite attempting to check i ...

Error: Module not found - The package path "." is not exported from the specified package. As a result, Firebase will not update in your Next.js

I have been developing a Next.js application that retrieves data from a Firebase collection. During the process of connecting to the Firebase database, I have come across the following error: Failed to compile. Module not found This error seems to be ori ...

Removing entries in a Google spreadsheet by utilizing the API and executing a BatchUpdateRequest

Currently, I am working on sending a BatchUpdateRequest to the Google Sheets API in order to delete a row of data from a spreadsheet. Here is how my request is structured: var spreadsheetId = '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI'; ...

Building dynamic multi-level lists in Python: A step-by-step guide

While I've seen several questions similar to mine, I have yet to find a satisfactory answer. I am attempting to populate a list with other lists dynamically, but for some reason, my code isn't behaving as expected. This is my code: x = [1,2,3] ...

Unexpected syntax error encountered when shutting down the route, unable to recover

const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.get('/split/name', (req, res) => ...

Angular allows for a maximum time span of 60 days between two date inputs

I am looking to implement a validation in JavaScript or TypeScript for Angular where the start date cannot be more than 60 days after the end date is entered. The requirement is to enforce a "maximum range of 60 days" between the two input dates (dateFro ...

Updating token (JWT) using interceptor in Angular 6

At first, I had a function that checked for the existence of a token and if it wasn't present, redirected the user to the login page. Now, I need to incorporate the logic of token refreshing when it expires using a refresh token. However, I'm enc ...

The Angular service "this" is altering the context of the window object

I must have made a mistake somewhere and I know I am overlooking something obvious. The aim is to create a service that provides basic authentication features such as login, logout, and checking if a user is logged in or not. Upon loading the page, I veri ...

Issue arising during reconnection following a disconnection in the node-redis client

I'm struggling to understand why the SocketClosedUnexpectedlyError error is being triggered in the code snippet below: const redisClient = require('redis').createClient(); redisClient.connect().then(function() { return redisClient.disconn ...

Is there a way to display the true colors of a picture thumbnail when we click on it?

In my project, I attempted to create a dynamic color change effect when clicking on one of four different pictures. The images are displayed as thumbnails, and upon clicking on a thumbnail, it becomes active with the corresponding logo color, similar to t ...

Issue with displaying content using v-show in a Nuxt.js menu

Struggling to create a mobile menu with Vue instance error The Nuxt Menu Component : <template> <header id="menu" class="menu-g"> <Nuxt-link to="/"><img src="~assets/logo.svg" alt=&qu ...

Loading Bootstrap accordion content with AJAX only when clicked

Is there a way to load ajax content into an accordion only when it is active? This could help prevent unnecessary data loading. It would be helpful to have a spinner displayed while the content is loading. I've searched online but haven't found a ...

Bring in styles from the API within Angular

My goal is to retrieve styles from an API and dynamically render components based on those styles. import { Component } from '@angular/core'; import { StyleService } from "./style.service"; import { Style } from "./models/style"; @Component({ ...

Adding several lines of HTML content from an object using jQuery's append method

Currently, this is what I have: $(document).ready(function() { $.ajax({ type:"GET" , url:'{{url("/api/getcart")}}' , dataType:"json", success: function(data){ $('#price').append(data.cartitems[1].product.pr ...

Conceal the Addon Tab across all pages in Storybook

Is there a way to globally hide an Addon Tab without disabling the addon itself? Specifically, I am using version 5.3.18 of Storybook with React and I want to hide the tab panel from the addon "styled-component theme". I apologize for the basic question, ...