Update the value in a nested object array by cross-referencing it with a second nested object array and inserting the object into the specified

I have a large array of objects with over 10,000 records. Each object contains an array in a specific key value, which needs to be iterated and compared with another array of objects. If there is a match, I want to replace that value with the corresponding object from the comparison array.

Here is an example:

obj1 = [{
  "control_id": "red1234",
  "security_domain": "astrem",
  "control_statement": "testing",
  "descriptio": "test",
  "label": "minimal",
  "technologies": [
    "180"
  ],
  "reference": {
    "string": "string"
  },
  "evaluation": "",
  "category": null
}, {
  "control_id": "red1234",
  "security_domain": "astrem",
  "control_statement": "testing",
  "descriptio": "test",
  "label": "minimal",
  "technologies": [
    "180", "320","3213"
  ],
  "reference": {
    "string": "string"
  },
  "evaluation": "",
  "category": null
}]
obj2 = [
  {
    "id": 94,
    "name": "SUSE Linux Enterprise 12.x"
  },
  {
    "id": 174,
    "name": "Ubuntu 18.x"
  },
  ...
]

In obj1, compare the array of technologies with the array of objects in obj2 using IDs. If there is a match, push the matched object into obj1.

The desired output should look like this:

obj1 = [
  {
    "control_id": "red1234",
    "security_domain": "astrem",
    "control_statement": "testing",
    "descriptio": "test",
    "label": "minimal",
    "technologies": [
      {
        "id": 180,
        "name": "Windows 2019 Server"
      }
    ],
    "reference": {
      "string": "string"
    },
    "evaluation": "",
    "category": null
  },
  {
    "control_id": "red1234",
    "security_domain": "astrem",
    "control_statement": "testing",
    "descriptio": "test",
    "label": "minimal",
    "technologies": [
      {
        "id": 180,
        "name": "Windows 2019 Server"
      },
      {
        "id": 320,
        "name": "Windows 2012 Server"
      },
      {
        "id": 3213,
        "name": "Windows 1999 Server"
      }
    ],
    "reference": {
      "string": "string"
    },
    "evaluation": "",
    "category": null
  }
]

I attempted to achieve this with the following code snippet:

obj1.map(element => element.technologies.forEach((techArrayList, index) => 
     this.operatingSystem.find(o => {
      if (techArrayList == o.id) {
         obj1[element.technologies].technologies[index].replace(o);
      }
     })));

Answer №1

My approach to this situation would involve the following steps...

/**
 * To simplify and expedite the process, I suggest creating an object with key-value pairs for easy reference:
 * {
 *   1: { id: 1, name: 'Windows Platforms },
 *   2: { id: 2, name: 'Linux Platforms' }
 *   ...
 * }
 */
const technologyMap = obj2.reduce((accumulator, technology) => {
    // For each item in the array, add a new property to the technologyMap using the 'id' as the key
    // This allows direct access to the original object by referencing technologyMap['1']
    accumulator[technology['id']] = { ...technology };
    return accumulator;
}, {});

/**
 * Generate a new list by replacing all technology ids with their corresponding objects
 */
const newBigDataList = obj1.map((dataItem) => {
    const technologies = dataItem.technologies.map((techId) => ({ ...technologyMap[techId] }));
    
    // Return a new object with all properties from dataItem but with updated technologies array
    return { ...dataItem, technologies };
});

/**
 * If the big data list is large and you prefer not to create a new list, you can update the technologies arrays directly
 */
obj1.forEach((dataItem) => {
    const technologies = dataItem.technologies.map((techId) => ({ ...technologyMap[techId] }));

    // Update the existing dataItem with the new array of technology objects
    dataItem.technologies = technologies;
});

Answer №2

Start by mapping the value from obj1 and searching for it in obj2

obj1.forEach((o) => {
      let newArr = o.key.map((k) => {
        const foundObject = obj2.find((ele) => {
          return ele.id == k;
        });
        return foundObject;
      });
      o.key = newArr;
    });

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

Guide to encoding an array of objects into a URI-friendly query string using TypeScript

Just getting started with typescript and looking for some help. I have an input array structured like this: filter = [ { field : "eventId", value : "123" }, { field : "baseLocation", value : "singapore" } ] The desired format for ...

The property in the object cannot be assigned because it is read-only: [object Object]

I am currently developing an Ionic application using the Angular framework and NGRX. I have encountered an issue with a selected checkbox. The problem arises when: First, I fetch a list of vehicles from a database using a service. Then, I set the propert ...

Modify the css with JQUERY when there are no rows inside the tbody section

Is it possible to change the css using jquery if there are no rows in the table body? I have attempted this but my current approach is not working. I tried adding an alert within the if statement, but the alert did not appear. My goal is to hide the table ...

Ways to reset the selected option when the user chooses a different option using either Jquery or Vanilla JavaScript

I am currently working on a functionality to clear the select option when a different brand is selected. The issue I am facing is that when I choose another brand, the models from the previous selection are not cleared out. For example, if I select BMW, I ...

What is the best method for loading multiple HTML files into a Div container?

Recently, I made the decision to improve the look of an online manual I have been working on for my company by incorporating Bootstrap. The manual is structured with a tree-view that contains titles linking to HTML files with information and CSS stylesheet ...

When updating the data in a datatables.net table within Angular 7, the previous data from the initial table load is retained

I'm currently working on a project that involves live reporting from a REST API request using the datatables.net library in Angular 7. When I update data in the database, the table reflects these changes accurately. However, if I interact with the tab ...

Finding the occurrences of elements in an array using JavaScript

While browsing Stack Overflow, I stumbled upon a question that has yet to be answered: How can I count the occurrences of elements in a specific array using JavaScript?. let array = [6, 1, 5, 1, 1, 8, 2, 4, 6, 0] // Elements in array getOccurrence(array) ...

Display tab content in Vue.js upon clicking

I'm encountering an issue with my Vue.js code. I want to display specific content every time I click on a tab. Here's the code snippet I have written: <template> <nav class="horizontal top-border block-section"> <div class= ...

The absence of a defined window - react-draft-wysiwyg integration with Next.js (SSR) is causing issues

Currently, I am in the process of developing a rich text editor that is used to convert plain HTML into editor content using Next.js for SSR. While working on this project, I encountered an error stating "window is not defined," prompting me to search for ...

The basic function is ineffective when used within an if-condition

I am currently dealing with a JSON file that has some nesting: { "name": "1370", "children": [ { "name": "Position X", "value": -1 }, {...} ] "matches": [ { "certainty": 100, "match": { "name": "1370 ...

npm unable to locate a JavaScript file

Currently, I am developing an Angular 2 application that utilizes the ng2-slugify package. However, I have encountered an issue where it cannot locate one of the required slugify files, specifically "charmaps.js", even though it is stored in the same direc ...

Searching for a specific data point within the latest entry of a JSON file using Javascript

I am currently in the process of utilizing a sensor to measure temperature, which is then stored in a mongo database. This data can be accessed as a JSON file by visiting ('/data'). My goal is to determine the latest entry and extract the temper ...

Is there a way to effectively sort through Firebase database entries using Angular based on checkbox selection?

I am working on an event page where all events are displayed with a category field. This is how my database structure looks: category: - categoryName events: - eventName - category.id (stores the category id) My goal is to initially display all eve ...

A step-by-step guide on transferring data from a dynamic user interface to a server using React Native

In the following code snippet, I am dynamically retrieving an array value to generate a user interface. The UI will vary based on the dynamic nature of this value. However, I'm facing confusion regarding how to upload all the data to the server upon ...

Utilizing precise data types for return values in React hooks with Typescript based on argument types

I developed a react hook that resembles the following structure: export const useForm = <T>(values: T) => { const [formData, setFormData] = useState<FormFieldData<T>>({}); useEffect(() => { const fields = {}; for (const ...

What could be causing the triggering of two AJAX requests in the given JavaScript code?

I have a code snippet that fetches data from the server. I want to trigger it on document.ready(). My expectation is that the first request is sent to the server, receives a response, and then the second request is made, and so forth. However, when I insp ...

A possible invocation of a function using a JavaScript "class"

Presented here is a node module I've been working on: var _ = require('lodash'); function Config(configType, configDir) { this.configType = configType; this.configDir = configDir; }; Config.prototype.read = function() { // read file t ...

Switching Tabs When a Button is Clicked

I am currently using a guide from the link provided to learn how to create tabs: http://www.w3schools.com/howto/howto_js_tabs.asp. function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClass ...

Guide to rendering a div class conditionally in a Razor page depending on a variable?

How can I dynamically render a div with different classes in Angular based on a condition? <div class="@(myArray.length>0 ? "col-md-8" : "col-md-12" )"> I'm trying to achieve that if the length of myArray is greater than 0, then it should h ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...