Replacing values between Arrays and Objects

I currently possess a lookupMap variable that contains an index of counties and their corresponding codes. Here is a snippet:

{ ANDERSON: { county: 'ANDERSON', code: 'us-tx-001' },  
ANDREWS: { county: 'ANDREWS', code: 'us-tx-003' } ,
WARD: { county: 'WARD', code: 'us-tx-475' },
WASHINGTON: { county: 'WASHINGTON', code: 'us-tx-477' },
WEBB: { county: 'WEBB', code: 'us-tx-479' }}

Though not all counties will be utilized, it serves as a useful reference.

In addition to this, I have another variable called uniquedata which consists of an array of codes:

[ 'us-tx-477', 'us-tx-479' ]

Furthermore, I have results stored in the var results variable like so:

{ WASHINGTON: 9, WEBB: 4 }

My task now is to iterate through each element in uniquedata, find its corresponding county name, and replace the county name with the code while keeping the count unchanged.

For instance, the expected output should look like this:

{ 'us-tx-477' : 9,
 'us-tx-479': 4}

Could you suggest the most effective approach for accomplishing this? I am encountering difficulties in isolating elements and finding the process rather perplexing. Your expertise would be greatly appreciated.

Answer №1

Loop through each item in uniquedata and perform a search in the data object. The method findInLookupMap scans through each entry in the lookupmap and retrieves the county name for a given code.

Here's an example snippet:

var cache = {}; 
function findInLookupMap(key){
  if(cache[key]) return cache[key]; // <--- Utilizing cache to avoid repeated searches
  for(var o in data){ 
    if(data[o].code == key){
      cache[key] = data[o].county;
      return data[o].county;
    }
  }
}

var output = {};
for(var i=0;i<uniquedata.length;i++){ // <--- Iterating over each item in uniquedata
  var code = findInLookupMap(uniquedata[i]);
  output[uniquedata[i]] = results[code];
}
console.log(output);

var lookupMap = {
  "ANDERSON": {
    "county": 'ANDERSON',
    "code": 'us-tx-001'
  },
  "ANDREWS": {
    "county": 'ANDREWS',
    "code": 'us-tx-003'
  },
  "WARD": {
    "county": 'WARD',
    "code": 'us-tx-475'
  },
  "WASHINGTON": {
    "county": 'WASHINGTON',
    "code": 'us-tx-477'
  },
  "WEBB": {
    "county": 'WEBB',
    "code": 'us-tx-479'
  }
};
var uniquedata = ['us-tx-477', 'us-tx-479'];

var results = {
  WASHINGTON: 9,
  WEBB: 4
};
var cache = {};

function findInLookupMap(key) {
  if (cache[key]) return cache[key];
  for (var o in lookupMap) {
    if (lookupMap[o].code == key) {
      cache[key] = lookupMap[o].county;
      return lookupMap[o].county;
    }
  }
}
var output = {};
for (var i = 0; i < uniquedata.length; i++) {
  var code = findInLookupMap(uniquedata[i]);
  output[uniquedata[i]] = results[code];
}
console.log(output);

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

Is it advisable to combine/minimize JS/CSS that have already been minimized? If the answer is yes, what is

Our app currently relies on multiple JS library dependencies that have already been minified. We are considering consolidating them into a single file to streamline the downloading process for the browser. After exploring options like Google Closure Compi ...

How to troubleshoot console.log() not displaying in Vue.js files when using Node.js + Vue.js framework?

As a newcomer to JavaScript development, I find myself working on an interesting project. Let me provide some insights: The project consists of an Express (Node.js) server with a /public/app folder Another part of the project is a Vue.js application with ...

What is the best way to create a line break within a loop in React?

I have a react component that I need to format into multiple lines, specifically having 2 boxes on top and 3 below in a looped return. The desired layout is to stack the boxes in 2x2 or 2x3 depending on the total number of boxes generated by the loop. So, ...

We're sorry, but the server couldn't locate the URL you were looking for in React

I recently uploaded my React.js website to Strato, but I encountered an error. When I try to access a different page like /status, I get a "Not Found The requested URL was not found on this server" error message. The homepage works fine, but the route page ...

I attempted to create a callable function for creating a user, but I encountered an error when running it and I am unable to determine the cause

I'm in the process of creating a user management page and have set up a callable function on Firebase to handle the creation of new users. The HTML function I've designed is supposed to update existing users or create new ones. However, when test ...

Searching for a specific substring within a string using pointers in the C programming language

I am struggling to create a function that returns a pointer to a substring within a string without using integers or array indexing. Below is the code I have so far, but I am having trouble getting it to work properly. /* * Return a pointer to the firs ...

Why is it that I am unable to utilize the post data stored in $var within my PHP document when making an Ajax call?

Hey there! I've got this function that makes an ajax call. But, for some reason, the $value I'm passing isn't defined in my showuser.php file. Can you help me figure out why? function showUser2(value) { var xhr = new XMLHttp ...

Attempting to integrate a three.js OBJLoader within an HTML canvas

My issue is quite straightforward: I attempted to connect a three.js script with an HTML canvas, but I was unsuccessful and now I'm unsure how to proceed. Here is the code I have (I've already loaded the necessary scripts in the HTML head): wi ...

Storing JavaScript Array for Future Use in a Separate File

Trying to clarify my question: I'm working with two files: number-crunching.js and chart.html. The number-crunching.js file contains a JSON object: var data = [ { "mother": "Ellen", "father": "Bob", "pet": "cat", "age":50, "hairLength":10 ...

The getHours function seems to be malfunctioning when calculating the difference between dates

[code][1] Hello, I am currently working on calculating the difference between two dates and I want the result to be displayed in the format 00:00:00. Currently, my "current" time is set as 00:00:00 but I need it to dynamically update based on the hours, m ...

Java script button click event is not functioning in IE 9 as expected

Here is the JavaScript code I am using: document.getElementById("<%= btnUpload.ClientID %>").click(); The functionality works flawlessly on all browsers except for Internet Explorer 9. What could possibly be causing this issue? ...

`The simultaneous processing of two inputs using forkJoin`

There are two input fields on my form: Street address and Zipcode. Each field emits its value on keyup as a Subject in Angular. Before calling an API endpoint with these values, I need to ensure that both the street address and zip code values are valid. ...

Displaying a hand cursor on a bar chart when hovered over in c3.js

When using pie charts in c3js, a hand cursor (pointer) is displayed by default when hovering over a pie slice. I am looking to achieve the same behavior for each bar in a bar chart. How can this be done? I attempted the CSS below, but it resulted in the h ...

Using JavaScript to set a form via a parameter in the URL

Is there a way to dynamically change the SetForm based on a parameter in the URL, such as radio.php?land=form2? I tried doing it this way but it doesn't seem to work. However, when I do it manually via the menu, it works. This is my first time attemp ...

Unable to conceal element if it is devoid of content

<div id="web-link" class="infoline"> <i class="fa fa-link fa-2x fa-fw coloriconfa"></i> <a href="<?=$data['post']['url']?>" target="_blank"><?=$data[ ...

Guide to retrieving a vector from a function

I am encountering some issues while attempting to return a vector from a function. Currently, this is the best approach I have: int* OptimizedSkillLevels(int skillLevel, const int numSkills, int duration, FragmentOptimizationParameters FOP){ //s ...

In the event that the identifier changes, initiate a fresh iteration of the loop

My query is returning several lines with the same id. Here's an example of the output: Id Amount Owed Description 552 50.00 Diapers 552 35.00 Lotion 545 23.00 Pen 545 15.00 Notebook Currently, I'm looping in Javascript to display t ...

Randomize checkbox selection using Javascript and Bootstrap

I'm in a bit of a bind with my webpage and could really use some help to figure it out. Here's the issue: On my website, there's a table of players. Each player has two checkboxes on their line: one to show if they are active (checked), and ...

Explaining the process of defining `this.props` and storing data in the global Redux state

I am currently diving into the world of react and Redux and I'm using a react project on GitHub called overcode/rovercode-ui as a learning tool for understanding react and Redux. As I explore this project, I have come across some intriguing questions. ...

Utilizing jQuery to submit the form

After clicking the search icon, it displays an alert with the message ok, but not h. Based on the code snippet below, it is intended to display alerts for both ok and h. <?php if(isset($_POST['search'])){ echo "<script type='text/ ...