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

Using the TIMESTAMP data type in PostgreSQL and getting the most out of it

After saving a Luxon datetime value in a TIMESTAMP(3) type column in a postgres database, I encountered difficulty using it for various operations like converting time zones. Despite creating the object with the code snippet below: const { DateTime } = req ...

Assign a value to the input field based on changes made in another input field

I am brand new to the world of JavaScript and currently grappling with setting a value in an input field based on the onchange event of another input field. Here is my code sample for input field 1: <input type='text' onchange='methodTh ...

Issue with inline Javascript not functioning correctly when partial is rerendered in Ruby on Rails version 3.1

I am facing an issue in my project where inline JavaScript in a partial, using some instance variables, does not run when the partial is rerendered after a successful ajax call. Could someone please provide guidance on how to solve this problem? For exam ...

Developing a custom CSS for React using clamp and focus attributes

I'm currently working on creating an object to be used in inline style, but I'm having trouble figuring out how to correctly write `clamp` and `after`. const PhoneInputStyle = { fontSize: clamp("13px", "1.111vw", "16px"), /*this particular ...

Is there a way to retrieve the form name within my directive?

In my code, I am able to retrieve the ngModel name, but now I am looking for a way to also capture the form's name that contains the element with the "validacion" directive. It is crucial for me to programmatically obtain the form's name where t ...

Iterate through the Ionic3/Angular4 object using a loop

I've been attempting to cycle through some content. While I tried a few solutions from StackOverflow, none seem to be effective in my case. Here is the JSON data I am working with: { "-KmdNgomUUnfV8fkzne_":{ "name":"Abastecimento" }, ...

TSConfig - Automatically Generates a ".js" File for Every ".ts" File

Having a unique software application with an unconventional file structure project ├── tsconfig.json ├── app_1 │ ├── ts │ └── js | └── app_2 ├── ts └── js I aim to compile files located inside the ...

Why don't I need to include an onload event to execute the setInterval() method within the script tag?

Hey there! I'm diving into the world of Javascript and I've come across this interesting code that changes an image every four seconds. Surprisingly, it's working perfectly fine even though I didn't include an onload event to execute th ...

Storing the order of jQuery UI Sortable in the WordPress Admin Panel

My goal is to customize the order of taxonomy terms for each individual post in Wordpress. I have created a metabox on the EDIT POST page that contains custom taxonomy terms and made them sortable using JQuery. Here is my setup on the Wordpress backend: ...

Why won't my picture track the movement of the cursor?

I am trying to make my image follow the cursor using a specific code, but it doesn't seem to be working. I'm having trouble figuring out what's wrong with it. Here is the code snippet that I'm currently using: function followIt(e) ...

Experience the simplicity of running basic Javascript Scratch code within IntelliJ IDEA Ultimate

Is there a straightforward way to run and debug a basic JavaScript code in IntelliJ Idea Ultimate without the need for additional setup like creating an HTML file or npm project? I'm looking to avoid boilerplate tasks and wondering if there's an ...

When the progress bar is clicked, the background color changes and then changes back again

https://www.w3schools.com/code/tryit.asp?filename=FG1ZE0NJ4ZX7 https://i.stack.imgur.com/Bnd0k.png I have created a progress bar that resembles the screenshot provided. When I hover over it, the color changes to green. However, I am looking for assistanc ...

Utilizing an Array of objects in conjunction with $.when

I have a list of Ajax requests stored in an Array, and I need to wait for all of them to finish loading before processing the results. Here is the code snippet I am currently using: $.when( RequestArray ).done(function(){ this.processResu ...

Having trouble implementing the page object model with cucumber.js: bug detected!

I have been working on implementing a page object pattern in my cucumber.js test automation suite with selenium webdriver. However, I am facing an error when trying to call the page object from my test step. The folder structure I am using is as follows: ...

Tips for implementing two functions to run within the onClick event handler in React

I am looking to simultaneously execute two functions handleClose and saveData within the onClick method. The specific location where I want this execution to happen: <Button variant="contained" onClick={saveData}&g ...

Javascript datatables do not allow for setting a default column sort

I am encountering an issue where I need to sort the results by a specific column on page load. In this case, I want the initial results to be displayed in descending order based on "RecordDate". However, it seems that the server side is blocking any sort ...

Create a custom VueJS component by utilizing an npm package

Looking to navigate around X-frame restrictions? You can check out this npm package: https://www.npmjs.com/package/x-frame-bypass To make it work, include the following tag within your HTML: <iframe is="x-frame-bypass" src="https://example.org/">& ...

Express Validator: The Art of Isolating Validation Logic

This query is more focused on structuring code rather than troubleshooting bugs or errors. I am currently tackling request body validation, where the JSON structure looks like this: { "title": "Beetlejuice", "year&qu ...

How to use JQuery to parse an external JSON file with array elements in Javascript

My goal is to extract information from an external JSON file using JavaScript, specifically an array and other elements. The JSON file I am working with is called 'TotalUsers.json' {"@version":"1.0", "@generatedDate":"12/20/10 5:24 PM", "day":[{ ...

Keep the sub-menu in a kendo context menu from closing until the user either hovers over another menu item or clicks outside of the current item

Please take a look at this example: Due to the small size of sub-items, the sub-menu closes quickly when hovering over the menu and losing focus. My goal is to keep an opened sub-menu from closing until the user hovers over another menu item or clicks on ...