Combining two JSON objects in JavaScript is simple when their IDs correspond to each other in both objects

I have a query related to merging two different objects from the database, both in JSON format.

These two objects share two key/value pairs: IRBId = ... and id = ..., which can be seen in the examples below:

OBJ 1

{
   "data":{
      "IRBs":{
         "nodes":[
            {
               "id":"8",
               "name":"Admin",
            },
            {
               "id":"9",
               "name":"Again",
            }
         ]
      }
   }
}

OBJ 2

{
   "data":{
      "informedConsentForms":{
         "count":3,
         "nodes":[
            {
               "id":"93",
               ...
               "IRBId":"9",
            },
            {
               "id":"92",
               ...
               "IRBId":"8",
            },
            {
               "id":"91",
               ...
               "IRBId":"8",
            }
         ]
      }
   }

It is evident that OBJ 2 and OBJ 1 correspond with each other based on the matching IRBid and id values.

The desired outcome is to merge these two objects where IRBId OBJ 2 === id OBJ 1.

The expected result after the merge would look like this:

Merged OBJ

 {
            [{
               "id":"93",
                ...
               "IRBId":"9",
               "irb": {
                 "name":"Again",
                 ...
               }
            },
            {
               "id":"92",
               ...
               "IRBId":"8",
               "irb": {
                 "name":"Admin",
                 ...
               }
            },
            {
               "id":"91",
               ...
               "IRBId":"8",
               "irb": {
                 "name":"Admin",
                 ...
            }
         ]
   }

I am unsure how to achieve this specific formatting. Please assist.

Answer №1

Consider utilizing the Array.reduce method for implementing this logic.

  • Iterate through the data nodes of the second object.
  • Identify the corresponding nodes in the data nodes of the first object.
  • Add the necessary details to the accumulator. (Note: Only the nodes mentioned in the expected result have been included, additional nodes can be added as needed.)

const obj1 = {
  "data": {
    "IRBs": {
      "nodes": [
        {
          "id": "8",
          "name": "Admin ",
        },
        {
          "id": "9",
          "name": "Again",
        }
      ],
    }
  }
}
const obj2 = {
  "data": {
    "informedConsentForms": {
      "count": 3,
      "nodes": [
        {
          "id": "93",
          "IRBId": "9",
        },
        {
          "id": "92",
          "IRBId": "8",
        },
        {
          "id": "91",
          "IRBId": "8",
        }
      ],
    }
  },
};

const obj1List = obj1.data.IRBs.nodes;
const output = obj2.data.informedConsentForms.nodes.reduce((acc, curr) => {
  const matchingNode = obj1List.find((item) => item.id === curr.IRBId);
  if (matchingNode) {
    acc.push({
      id: curr.id,
      IRBId: curr.IRBId,
      irb: {
        name: matchingNode.name
      }
    })
  }
  return acc;
}, []);
console.log(output);

Answer №2

To create a new object that combines the attributes of two existing objects, you can utilize the map function on the nodes within the first object.

const obj1 = {
  "data": {
    "IRBs": {
      "nodes": [{
          "id": "8",
          "obj1": "one",
          "name": "Admin ",
        },
        {
          "id": "9",
          "obj1": "two",
          "name": "Again",
        }
      ]
    }
  }
};

const obj2 = {
  "data": {
    "informedConsentForms": {
      "count": 3,
      "nodes": [{
          "id": "93",
          "obj2": "1",
          "IRBId": "9",
        },
        {
          "id": "92",
          "obj2": "2",
          "IRBId": "8",
        },
        {
          "id": "91",
          "obj2": "3",
          "IRBId": "8",
        }
      ],
    }
  }
};
const obj1Data = obj1.data.IRBs.nodes;
const obj2Data = obj2.data.informedConsentForms.nodes;
const res = obj2Data.map(item => {
  const obj1Item = obj1Data.find(obj1Item => item.IRBId === obj1Item.id);
  return obj1Item ? { ...item, "irb": { ...obj1Item}} : { ...item};
});
console.log(res);

Answer №3

Here is an example of using nested loops:

const obj2 = {
   "data":{
      "informedConsentForms":{
         "count":3,
         "nodes":[
            {
               "id":"93",
               "IRBId":"9",
            },
            {
               "id":"92",
               "IRBId":"8",
            },
            {
               "id":"91",
               "IRBId":"8",
            }
         ],
      }
   },
}

const obj1 = {
   "data":{
      "IRBs":{
         "nodes":[
            {
               "id":"8",
               "name":"Admin ",
            },
            {
               "id":"9",
               "name":"Again",
            }
         ],
      }
   }
}

const result = [];
const obj2Nodes = obj2.data.informedConsentForms.nodes;
for(let i = 0; i <  obj2Nodes.length; i++) {
    const obj1Nodes = obj1.data.IRBs.nodes
    for(let j = 0; j < obj1Nodes.length; j++) {
        if(obj2Nodes[i].IRBId === obj1Nodes[j].id) {
            const {id, ...reObj1Nodes} = obj1Nodes[j];
            result.push({
                ...obj2Nodes[i],
                'irb': {
                    ...reObj1Nodes
                }
            })
        }
    }
}
console.log(result)

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

Navigating a JSON object in ReactJS: key and value retrieval

Objective: Retrieve key and value pairs from JSON data using ReactJS. When the value is accessed with this code={this.state.myData}, it returns the following JSON data: "list":[ { "id": "1", "first_name": "FirstName", "last_name": "LastName ...

Rails converts the database variable names and values

In my project, I am facing a challenge where I need to modify the name/value of a property in a class that is sourced from a database. This issue arises because there are two versions of an application accessing the same database, with the newer version ha ...

Utilizing a functional component to incorporate a "load more" button in ReactJS

Hey everyone, I've come across this ReactJS code that I need some help with: function DisplaySolutions({solutions}) { const topSolutions = solutions.slice(0, 4); const remainingSolutions = solutions.slice(4); const [isD ...

Having trouble making the menu stay at the top of the page in IE7

Check out the demo here: http://jsfiddle.net/auMd5/ I'm looking to have the blue menu bar stay fixed to the top of the page as you scroll past it, and then return to its original position when scrolling back up. This functionality works in all brows ...

Error: The code is trying to access the property 'string' of an undefined variable. To fix this issue, make sure to

I encountered an issue after installing the https://github.com/yuanyan/boron library. The error message I received is: TypeError: Cannot read property 'string' of undefined Error details: push../node_modules/boron/modalFactory.js.module.expor ...

Using jQuery to remove an iframe upon a click event

My goal is to remove an iframe whenever anything on the page is clicked. I tried using this code: $('*').on('click',function(){ $('iframe').remove(); }); However, I encountered a problem where the i ...

Showcasing a JavaScript array retrieved through JSON on a web page

Apologies if I am causing any inconvenience again =x Thanks to the assistance from everyone, especially Scott Harwell, I successfully passed my php array to a js array using the code below: var horse_array = <?php echo json_encode($horse_info);?>; ...

What is the best way to reset form after submission in Next.js?

I have a contact form and I want all the form values to be cleared after submitting the form. I've tried the following code, but the values of the form remain unchanged after submission. What could be causing this issue and how can it be resolved? ...

Difficulty with formatting decimal points in JavaScript

I seem to be having an issue with decimal places in my code. Currently, it's showing the result as 123 123 12 but I actually need it to be displayed as 12 312 312. Is there anyone who can assist me with formatting this correctly? Here is the section ...

Retrieve the property value from a nested object using a key that contains spaces

Presenting my object: let obj = { innerObj: { "Key with spaces": "Value you seek" } } Upon receiving, I am unaware of the content within obj. I possess a string variable holding the key to access the value. It appears as follows: let ke ...

Learn the process of invoking an Angular scope function from within a JavaScript function located within a controller

In my Angular controller, I have a JavaScript function where I am trying to call an Angular function. However, I am encountering the error: $scope.Name is not a function, $scope.dates is not a function. function validation() { $scope.page ...

How can I dynamically insert a new HTML element into $event.target using Angular 2?

I have a webpage with a list of items. I want to display a "copy" button next to each item when the mouse hovers over it. I am currently able to create the "copy" button within the element using the following method: mouseOver(event) { if (event.tar ...

Tips for making sure there is a delay in between each axios call in a React

Currently in the process of developing an application that needs to interact with a RestAPI by sending a specific set of inputs. However, the API has a major flaw when it comes to scalability and tends to respond with code 429 if bombarded with too many re ...

Utilize JavaScript and jQuery to locate a particular character within a string and move it one position back in the sequence

Can you locate a particular character within a string and move it to the position before? For instance: Consider the following string: Kù Iù Mù The desired output is: ùK ùI ùM ...

Angular.js - index template fails to execute controller, but other templates work flawlessly

I am facing a strange issue with my Angular application that uses ngRoute. I have set up different controllers for each template in the routes.js file: routes.js: angular.module('PokeApp', ['ngRoute']) .config(function($routeProvide ...

Change the CSS menu item to directly load the website instead of using javascript to replace a placeholder

I have a CSS navigation menu, but I'm facing an issue. When I click on a link in the menu, like Google for example, it only changes the name of the placeholder and doesn't actually load the page. Any suggestions on how to fix this? Thank you for ...

Is there a way to use regex to selectively color JSON keys?

My goal in JavaScript is to extract all of the JSON keys using regular expressions. I am assuming that the JSON data will be formatted with each key-value pair on a new line, like this: { "name": "Jane", "age": 30, } In simple terms, I am looking ...

Using ReactJS and JavaScript to transform an array into a fresh array

I am working with an array that looks like this: var oldArray = [ {number: '12345', alphabet: 'abcde'}, {number: '54321', alphabet: 'abcde'}, {number: '67891', alphabet: 'abcde'}, ...

The use of a map with Next/image seems to be preventing the src image from loading properly

Utilizing next/image for loading images in my application has been successful, except when it comes to a carousel featuring multiple images. Whenever I attempt this, I encounter the following error: Error: Image is missing required "src" property. Make su ...

Utilize a personalized useFetch hook in React.js to transmit a POST request and obtain a response

I recently came across a great resource on this website that provided the logic for a useFetch hook. My goal is simple - I want to send a post request and then map the response into a specific type. While this seems like it should be straightforward, I&apo ...