Analyzing the values of two sets of key-value pairs

I am facing an issue where I have two sets of objects labeled LABELS1 and LABELS2, and my goal is to iterate through them. If any of the IDs from LABELS1 match any of the IDs from LABEL2, I need to update the simple_value of LABELS1 with the corresponding value from LABELS2. However, despite my attempts, the comparison always fails. Below is the code I have been working on. Any assistance in resolving this matter would be greatly appreciated.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">

    const LABELS1 = [
{"id":"bread", "simple_value":"Bread"},
{"id":"apple", "simple_value":"Apple"}
];
    const LABELS2 = [
{"id":"bread", "simple_value":"Bread with Butter", "detailed_value":"Toasted Bread with a Dab of Butter"},
{"id":"wine", "simple_value":"Wine", "detailed_value":"Wine with Cheese"}
];
    var labels1= [];
    var labels2= [];
        
    $.when(
    $.getJSON(LABELS1, json => {
       labels1= json;
    }), 
    $.getJSON(LABELS2, json => {       
      labels2= json; 
    })
    ).then(() => {
      Object.keys(labels1).forEach(key => {
         if (labels2[key].id=== labels1[key].id) {
            labels1[key].simple_value= labels2[key].simple_value;
         }
     });      
    });

</script>
</body>
</html>

Answer №1

Object.keys(labels1) will give you an array of item indexes rather than IDs because labels1 and labels2 are both arrays. You need to iterate through all the items in one array and look for a matching item in the other.

const LABELS1 = [
{"id":"bread", "simple_value":"Bread"},
{"id":"apple", "simple_value":"Apple"}
];
    const LABELS2 = [
{"id":"bread", "simple_value":"Bread with Butter", "detailed_value":"Toasted Bread with a Dab of Butter"},
{"id":"wine", "simple_value":"Wine", "detailed_value":"Wine with Cheese"}
];
    var labels1= LABELS1;
    var labels2= LABELS2;
        
      for(const label1 of labels1) {
        const label2Index = labels2.findIndex(label2 => label2.id === label1.id)
        if(label2Index != -1) {
          label1.simple_value = labels2[label2Index].simple_value
        }

      }
     console.log(labels1) 

    
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №2

To optimize performance, it is suggested to store the labels (#2) alongside their corresponding indices. This way, you can easily retrieve a label (#2) by its index while also mapping the labels (#1) to their respective simple_value.

const
  LABELS_1 = [
    { "id": "bread", "simple_value": "Bread" },
    { "id": "apple", "simple_value": "Apple" }
  ],
  LABELS_2 = [
    { "id": "bread", "simple_value": "Bread with Butter",
      "detailed_value":"Toasted Bread with a Dab of Butter" },
    { "id" :"wine", "simple_value": "Wine",
      "detailed_value": "Wine with Cheese" }
  ];

// Store the labels (#2) with their corresponding index
const idToIndex = LABELS_2.reduce((acc, { id }, index) =>
  ({ ...acc, [id]: index }), {});

const labels = LABELS_1.map(({ id, simple_value }) => ({
  id, simple_value: ((index) =>
    LABELS_2[index]?.simple_value || simple_value)
  (idToIndex[id]) 
}));

console.log(labels);
.as-console-wrapper { top: 0; max-height: 100% !important; }

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

Learn how to retrieve all offspring of a JSON object in C# by utilizing NewtonSoftJson

Welcome, User! Here is my JSON: I am trying to extract all usernames from the data list using C# and Newtonsoft.Json. I'm hopeful that someone can provide me with some guidance. I attempted the following approach but encountered issues: "kind":"Us ...

How can you generate a "Package Contains Lower Node Version" error message during the installation of an NPM package if the node version is higher than the current system's node version?

I am looking for a way to trigger an error during the installation of an NPM package if the node version supported by that module does not match the system/server node version. Specifically, I want to prevent the installation of any npm module that suppor ...

Alter the Color of the 'div' According to the Background

At the bottom right of my website, there is a black chatbot icon. The web footer also has a black background. To create a clear contrast, I have decided to change the color of the chatbot to white as users scroll to the bottom of the page. I implemented t ...

Implementing the insertion of a <div> element within an input field using jQuery

<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></scr ...

Code timer for HTML redirection

Some time ago, I created this code to display random events on my website. While the code functions well, I now wish to incorporate a timer. I envision that when a user refreshes or enters the page, they will be redirected initially and then redirected ag ...

Retrieving Information from MongoDB Collection with Paginated Results in Universal Sorted Sequence

I'm in the process of working on a project that involves a MongoDB collection called words, which holds a variety of words. My objective is to retrieve these words in a paginated manner while ensuring they are globally sorted in lexicographical order. ...

I have the ability to showcase information from a JSON file using AngularJS, although it may not be in the exact manner that

I am currently working with AngularJS 1.6.4 and NeDB. When attempting to retrieve all users from the database using NeDB, it returns a JSON file containing information for every user. I then tried to display this data using AngularJS, but when using ng-re ...

Exploring Angular $resource with a playful twist

Is there a recommended method for mocking the $resource object? I've looked online, but all my attempts ended with KARMA testing. It's not what I'm looking for. I'm thinking of creating a fake object so that I can easily switch betwee ...

The AJAX call in PHP is echoing JavaScript code that seems to be malfunctioning

Currently working on an AJAX page using php, where I plan to output a section of JS code upon completion. Despite having the JS code within the HTML page, it is not functioning properly. Any suggestions on how to get it to work? ...

What is the most effective way to update values in a JsonObject / JsonArray without using additional

If I have already converted a JSON String into a GSON provided JsonObject class (assuming I don't want to parse it into data objects and strictly want to use JsonObject), how can I directly modify a field/value of a key? I am unable to find an API th ...

What is the best way to defer the instantiation of a particular controller (not a route) in your

What I'm looking for is a directive that functions like a typical ng-controller, but I need it to be invoked only after a promise has been resolved. To achieve this in HTML, it could be implemented as such: <div ng-controller="myCtrl" ctrl-promise ...

Interacting with a button using Python Selenium while validating onFocus with JavaScript

I'm currently working on automating webpage navigation with Selenium in Python. My goal is to click on an HTML button that triggers JavaScript code to validate if the button is focused during the onclick action. Although I can successfully select a v ...

Is there a way to utilize Javascript to retrieve elements without specifying an id?

I am faced with a challenge of accessing an element without an id but with a shared classname using Javascript. How can I accomplish this task successfully? My attempt to use the document.getElementsbyClassName property was unsuccessful due to the shared ...

How can I dynamically assign ngModel in AngularJS?

I've created a directive with an isolate scope that maps a list of objects to inputs for modifying a specific property. However, I now aim to make this component more universal by allowing it to bind to deeply nested properties within each object. Fo ...

discord.js tutorial on cutting a hyperlink

i'm developing a Steam command that takes either the ID or profile link as arguments. My aim is to extract the last word. eg: https://steamcommunity.com/id/ethicalhackeryt/ here, I want to extract ethicalhackeryt or if the user directly inputs it the ...

Translating jsonObject into a Map in the Scala programming language

I am currently coding in Scala. I am looking for a way to convert a JSON object into a Map containing String keys and values. Here is an example of my jsonObject: {"Key1":"Val1","Key2":"Val2","Key3":"Val3"} I would like to transform it into a Map like ...

After the AJAX request, $this experienced a loss of focus

I am facing an issue with my CakePHP code snippet below: <tr class="tr_clone"> <td><?php echo $this->Form->input('items][',array('label'=>false,'options'=>$items,'class'=>'it ...

Retrieve the selected option value from a dropdown menu when hovering or making a change within the same event

Apologies for my poor English. Is there a way to retrieve the value of a select box when a user either changes the select box or hovers over it with just one event? I attempted the following code snippet but it did not work as expected: jQuery("select[nam ...

Unusual compilation issue encountered in Vue when trying to use a template for a slot

I encountered a strange issue where my Vue compiler was refusing to render the default named slot of a child component. Error: Codegen node is missing for element/if/for node. Apply appropriate transforms first. Even my VSCode highlighted this problem a ...