Combining various JSON data sets that share a common identifier

The initial JSON data is retrieved from the API through an HTTP call:

[
    {
        "clientid": 1,
        "clientname": "facebook",
        "forecasted": 18,
    },
    {
        "clientid": 2,
        "clientname": "youtube",
        "forecasted": 83,
    }
]

I then created a second JSON object to update the image associated with each client in the first JSON:

 [
        {
            "clientid": 1,
            "clientname": "facebook ",
            "img":"images/21747.jpg"
        },
        {
            "clientid": 2,
            "clientname": "youtube",
            "img": "images/youtube.svg"
        },
    ]

The next step involves matching both JSON objects based on their IDs and updating the images in the first JSON obtained from the API using the images from the second JSON.

app.factory('myFactory', function($http){
  return{

    client: function(callback){
        $http({
          method: "GET",
          url: "http://www.erek.co.za/api/..",
          cache:true
        }).then(callback);
    },  
    list: function(callback){
        $http({
          method: "GET",
          url: "data/Client.json",
          cache:true
        }).then(callback);
    } 
  };
});
app.controller('myController', function ($scope, myFactory) {
          myFactory.client(function(response){
              var data = response.data;
              $scope.myClients = data;
          })
          myFactory.list(function (response) {
            var data = response.data;
            $scope.dark = data;
          })
        });

HTML Code:

<div ng-repeat="client in myClients>
<a href="#{{client.clientid}}" 
  <div class="client-project-panel">
      <div class="client-logo-container">
          <div class="client-logo" >
              <img ng-src="{{dark[$index].img}}" alt="{{client.clientname}}">
           </div>
          <div class="project-forecasted">
             <h2 class="forecasted-value">{{client.forecasted}}%</h2>
             <p>Complete</p>
          </div>
      </div>
  </div>
</a>

Answer №1

To accomplish this task, utilize the Object.assign method.

let array1=[ { "clientid": 1, "clientname": "facebook", "forecasted": 18, }, { "clientid": 2, "clientname": "youtube", "forecasted": 83, } ]
let array2 = [ { "clientid": 1, "clientname": "facebook ", "img":"images/21747.jpg" }, { "clientid": 2, "clientname": "youtube", "img": "images/youtube.svg" } ]
 
var expected = array1.map(a => Object.assign(a, array2.find(b => b.clientid == a.clientid)));
console.log(expected);

Answer №2

myFactory.client(function(response){
          var data = response.data;
          var clientsData = data;
          // retrieve clients and their images
          myFactory.list(function (response) {
            var data = response.data;
            var clientImages = {}
            for(var i=0;i<data.length;i++){
                clientImages[data[i].clientid] = data[i].img
            }
            $scope.dark = clientImages
            $scope.myClients = clientsData
          })

})

To display the image, use {{dark[client.clientid]}}

Consider using ng-if="myClients" to show content only after fetching the 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

Setting the Date format of ASP.Net Web Services to ISO: A Step-by-Step Guide

Seeking guidance on how to configure the default date format of a web service to match the ISO date format. I believe it needs to be adjusted within the 'Web.Config' file. Additionally, I would like this setting to work seamlessly with JSON data. ...

Limiting the maximum date for a datepicker

Looking to customize my datepicker code so that maxDate is only applied when selector === '#Birth'. Any suggestions on how to accomplish this? function customdatepicker(selector) { $(selector).datepicker({ inline: true, showO ...

How come the Jquery :odd selector picks out the even elements?

<html> <head> <script type="text/javascript" src="jquery-1.7.1.js" ></script> <script type="text/javascript"> $(function() { $("p:odd").html('modified'); }); </script> </head> & ...

The removeAttribute function has the ability to remove the "disabled" attribute, but it does not have the capability to remove

When it comes to my JavaScript code, I have encountered an issue with two specific lines: document.getElementsByName('group')[0].removeAttribute('disabled'); document.getElementsByName('group')[0].removeAttribute('checke ...

Error Encountered: Invalid Parameter Type when Retrieving Item from AWS Dynamo

I've been facing issues when trying to establish a connection between my ReactJS application and AWS DynamoDB. Despite confirming the correctness of the API key, secret key, and region, I keep encountering an InvalidParameterType error. I have even at ...

Unable to instantiate FormData with the constructor

Within my Angular application, I have a basic form setup like this: <form [formGroup]="loginForm" (submit)="login()"> <div id="container-credentials"> <input type="text" name="username" formControlName="username"> <input typ ...

Exploring a nested JSON structure using AngularJS's Ng-Repeat directive

I am facing an issue with displaying all elements of subcategory using Ng-Repeat. I have managed to show all events from the selected category with this code, but I am unsure how to display all activities from a specific event. I currently have this code.. ...

Strategies for managing the outcome of the most recent asynchronous request in Angular?

Encountered a bug related to debounced input and response handling. A search input triggers server queries as you type with a debounce set to 300ms. However, there are instances of unexpected behavior: If a user types "ab", waits 300ms, then types "c" be ...

In a jQuery application, the action of adding text from an input field to a div is triggered by clicking a

It's possible this is a duplicate question, but none of the answers I found solved my issue. I'm attempting to create a jQuery script where text entered into a text box is appended to a div when a button is clicked. This is part of a game I' ...

Each time the page is refreshed, the most recent form data submitted is continually appended to an array

I have implemented a post request to add input data from a form. The entered data is stored in an array variable burg and then displayed on my index.handlebars view. Everything works as intended, but when the page is refreshed without any input in the form ...

Issue encountered when attempting to unzip a file of size 12 megabytes

I have been using a specific open source tool to unzip files, and it works well for zips ranging from 2-5 MB. However, I encountered an error when trying to unzip a zip file that was over 10 MB in size. Are there any more reliable open source options ava ...

Attach a single function to numerous events across various elements simultaneously

I want to attach a function to both the mouseout event of my <canvas> element, as well as to the blur and contextmenu events of my body. What is the best way to bind this function to multiple elements with different events for each? Appreciate any h ...

Using React to render JSON questions on multiple pages

I am encountering an issue with my JSON pages. On each page, I have the same JSON questions, but whenever I make modifications to the first page, all other pages end up getting the same values as the first one. Is there a way for me to create an array to ...

What is the process for searching a sentence and making replacements under certain conditions?

When it comes to the address: _# _, and for the specified phrase: _# some specific words _. I am looking to identify a phrase. if (phrase includes address) then delete the address. const stringVal = "being _#kind_, I am a _#kind_ _#man_, I love _#kind ...

Ways to automatically collapse an open navbar upon clicking outside of the navbar on an HTML website

Is there a way to automatically close an open collapsed navbar by clicking outside of the navbar element? It's currently only possible to open or close it by clicking on the navbar-toggle button. For an example and code, click here. I've attemp ...

Ways to prevent a button from being enabled until a 12-letter text is inputted

I need assistance with disabling a button until a minimum of 12 characters are entered into a text input field. The platform I am working on utilizes Bootstrap and allows for custom JavaScript implementation. Below is my code for a form builder that incl ...

Remove HTML tags from a table cell containing a combination of radio buttons and labels

Javascript Function: My JavaScript function posted below is designed to iterate through the column indexes specified in the 2nd parameter and also iterate through the element ids provided in the 3rd parameter. It will then populate the textbox, radiobutto ...

What is the best way to determine if this specific radio button has been selected?

I have been searching for solutions on stackoverflow, but haven't found anything helpful :( Currently, I am facing an issue with my HTML table that is loaded through an ajax request: <table class="table table-striped table-hover choix_annonce_tab ...

Sauce Labs encountering issues when running JavaScript code

Currently, I am using Selenium WebdriverJs along with Mocha to conduct tests on Sauce Labs via Travis CI. After isolating the issue without any project dependencies, I am seeking help. The interesting observation is that defining an additional object with ...

Is there a way to display the tooltip at all times in Chart.js version 3.7.1?

https://i.sstatic.net/Lmfqn.png [Chart.js 3.7.1] Is there a way to keep the tooltip always visible? I am looking for a method to have the tooltip constantly displayed. Additionally, I would like the text to be darkened only on today's date. Si ...