Merge two arrays together in Javascript by comparing and pairing corresponding elements

Dealing with two arrays here. One comes from an API and the other is fetched from Firebase. Both contain a common key, which is the TLD as illustrated below.

API Array

[
 {
  "TLD" : "com",
  "tld_type": 1,
 },
  "TLD" : "org",
  "tld_type" : 1,
 }
]

Firebase Array

[
  {
    "TLD" : "com",
    "register_price" : 14.99
  },
  {
    "TLD" : "org",
    "register_price" : 15.99
  }
]

The goal is to merge these arrays into one cohesive array like this:

[
    {
        "TLD" : "com",
        "tld_type" : 1,
        "register_price" : 14.99
    },
    {
        "TLD" : "org",
        "tld_type" : 1,
        "register_price" : 15.99
    }
]

I've tried using concact after some online research but it doesn't seem to consider the key while matching elements. Any thoughts on how to achieve this?

Answer №1

To combine data from two arrays and create a new object with corresponding keys and values, you can utilize the map function. This will generate a new array of objects containing the merged information.

let api = [{
    "tld": "com",
    "tld_type": 1,
  },
  {
    "tld": "org",
    "tld_type": 1,
  }
]
let fb = [{
    "TLD": "com",
    "register_price": 14.99
  },
  {
    "TLD": "org",
    "register_price": 15.99
  }
]

let k = api.map(function(item, index) {
  let obj = {};
  obj.tld = item.tld;
  obj['tld_type'] = item['tld_type'];
  obj['register_price'] = fb[index]['register_price']
  return obj;

});
console.log(k)

Answer №2

When facing this type of issue, there is no one-size-fits-all solution. One approach is to iterate through all elements and add a register_price property if it exists in the firebase array. A concise way to do this is:

let combined = apiArray.map(ele=>{
    let matchedElement = fbArray.find(e => e.TLD === ele.tld)
    if(matchedElement != undefined) ele.register_price = matchedElement.register_price
    return ele
})

If you need to merge all properties, not just register_price:

let combined = apiArray.map(ele=>{
    let matchedElement = fbArray.find(e => e.TLD === ele.tld)
    if(matchedElement != undefined) {
       let mergedObject = Object.assign(ele, matchedElement)
       return mergedObject
    }else{
       return ele
    }
})

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

Deleting items from an array in ReactJS

When retrieving a list of users from AWS Cognito, everything works flawlessly. However, the task of iterating over this array and removing users that do not match a specific Client ID is where I'm facing difficulties. What am I doing wrong in this sc ...

Utilizing AngularJS to make an API call with $http method and handling a

I am attempting to make a call to my webservice using "$http". When I use "$ajax", it works fine. Here is an example of jQuery $Ajax working correctly: $.ajax({ type: "Get", crossDomain: true, contentType: "application/json; chars ...

Ways to effortlessly activate an angular directive once the page has been fully loaded

I am facing an issue with a print directive that is triggered by the print="id" attribute within an <a></a> element. The button is contained in a modal that remains hidden from the user. I want the directive to execute as soon as the modal is l ...

IIFE and the Twitter share button are a powerful duo

As I experiment with this quick creation of mine, two questions have arisen. The first one is, how can I encapsulate all the JS code within an IIFE without breaking it? The second question is about finishing the twitter button to enable sharing the act ...

Remove elements generated by the .after method with Jquery

In my HTML file, I have a table with hard-coded column headers: <table id="debugger-table"> <tr> <th>Attribute</th> <th>Computed</th> <th>Correct</th> </tr> </table&g ...

Troubleshooting: Ruby on Rails and Bootstrap dropdown issue

Having some issues with implementing the bootstrap dropdown functionality in my Ruby on Rails application's navigation bar. I have made sure to include all necessary JavaScript files. Below is the code snippet: <div class="dropdown-toggle" d ...

Concealing scroll bars while still maintaining the ability to scroll by using overflow:scroll

Similar Question: How to hide the scrollbar while still allowing scrolling with mouse and keyboard I have created a sidebar for a web application that needs to enable users to scroll through it without displaying a scrollbar. The content is 500px high ...

Assistance Required in Turning Down Trade Requests on Steam That Involve Losing items

Currently, I have a code snippet from a Steam bot that processes incoming trade offers by accepting or declining them based on their state. However, my goal is to modify it in a way so that it automatically accepts trade offers where I receive items, but ...

Setting up the current user's location when loading a map with Angular-google-maps

I am currently utilizing the library in conjunction with the IONIC framework. To manually set the center of the map, I have implemented the following code snippet: .controller('mainCtrl', function($scope) { $scope.map = { cen ...

Is there a missing X-AppEngine-Region in the headers of the AppEngine application?

I've been trying to access the Region and Country in my request, but it seems like the X-AppEngine-Region and X-AppEngine-Country headers are missing. Sometimes I see headers like alt-svc content-length content-type date etag server status via ...

Using httpRequest to handle binary data in JavaScript

Having trouble deciphering the response of an http request that is a binary datastream representing a jpeg image, despite numerous attempts. Edit: Including the full code snippet below: xmlhttp = false; /*@cc_on@*/ /*@if (@_jscript_versio ...

Should I use graphite or make multiple AJAX calls for querying data?

I am currently exploring the potential advantages of using Graphite. My web application receives data through JavaScript Ajax calls and visualizes it using Highcharts. To generate each graph, Python runs 20 different queries on my SQL database. The ...

What is the best method to make an email address distinct?

<body> <p>Please input your email address:</p> <input id="email" style="margin-bottom: 20px; margin-top: 2px;" type="email" placeholder="Email Address"> <input onclick= "validateEmail(email)" type="su ...

What is the best way to pass my request data to my $scope variable?

I'm currently facing a challenge with this particular topic. My goal is to add the response data that I retrieve from Express to my angular $scope and then direct the user to their profile page. This is how my Controller Function is structured: $sc ...

performing a GET request directly from a <script> element in the index.html file

I am currently developing an application that utilizes Angular.js on the client side and Node Express on the server side. On my server side, I am using a staticAsset module. Within my index.html file, I have a lengthy list of JavaScript files that need t ...

What could be causing my jQuery function to not correctly update the class as specified?

Presented is a snippet of script that I execute at a specific moment by echoing it in PHP: echo "<script>$('.incorrect-guesses div:nth-child(2)').removeClass('empty-guess').addClass('incorrect-guess').text('2' ...

Storing a multi-dimensional array in PHP efficiently

My PHP data consists of user limits: $userLimit = array( "default" => array( "playlistLimit" => 1, "mediaLimit" => 2, ), "editor" => array( "playlist ...

Extract a property from a JSON object

Is there a way to access the href properties and use them to create multiple img elements with their sources set as the extracted href properties? I'm looking for a solution in either javascript or jQuery. I attempted the following code, but it didn& ...

Build a nested block containing a div, link, and image using jQuery or vanilla JavaScript

I have a button that, when clicked, generates a panel with 4 divs, multiple href links, and multiple images. I am new to web programming and understand that this functionality needs to be in the Javascript section, especially since it involves using jsPlum ...

Uncovering design elements from Material UI components

The AppBar component applies certain styles to children of specific types, but only works on direct children. <AppBar title="first" iconElementRight={ <FlatButton label="first" /> }/> <AppBar title="second" iconElementRight={ <di ...