Optimal method for transforming the values of an object or array in JavaScript

I have a group of values that need to be transformed into new values using a legend. The process might sound confusing at first, but it will become clear shortly. To achieve this, I've relied on associative arrays or objects in JavaScript to serve as my legend.

This method can be applied to individual strings, arrays like the one below, or even objects.

var legend = {
    "html": "html5",
    "css2": "css3",
    "javascript": "jquery"  
}

var old_array = new Array("html", "css2", "javascript");
var new_array = [];

max = old_array.length;

// iterate through original array values
for(i=0;i<max;i++){
    for(var val in legend){
            // loop through legend values and convert if there's a match
        if(old_array[i] === val){
            new_array[i] = legend[val];
        }
    }
}
console.log(new_array);
document.write(new_array);

If you run this code in firebug or jsfiddle, you'll see a new array with the updated values.

I opted for an object/associative array as my legend because of its scalability. If new values require conversion, it's easy to add them. This method is versatile and works for converting individual strings, arrays like above, or objects and their keys or values.

Is this the best approach for value conversion? Are there any other factors to consider? In PHP, which is another language I frequently use, could the same concept of using an associative array apply?

Thank you for your guidance and advice!

Cheers!

Answer №1

Utilize the object's power by avoiding unnecessary loops through it. Access keys directly for efficiency:

var legend = {
    "html": "html5",
    "css2": "css3",
    "javascript": "jquery"  
}

var old_array = new Array("html", "css2", "javascript");
var new_array = [];

max = old_array.length;

// iterate over values in the original array
for(var i=0;i<max;i++){
    // check if the array value is a key in the legend object
    if ([old_array[i] in legend) {
        new_array.push(legend[old_array[i]]);
    }
}
console.log(new_array);
document.write(new_array);

I've also updated it to utilize new_array.push() to prevent undefined values in the resulting array. However, I'm unsure about the specific end result you're aiming for.

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

npm not only loads the packages specified in my package.json file

Currently, I am working on a small project utilizing npm, bower, and grunt. Upon executing "npm install" on my personal computer, it seems to be loading an excessive amount of peculiar items (refer to attached screenshot). However, when performing the same ...

Stopping free jqgrid disabled toolbar buttons from reacting to mouse clicks can be achieved by implementing specific coding techniques that

When using Free jqgrid, toolbar disabled buttons may trigger click events on mouse clicks which can lead to invalid code execution. To demonstrate this, open the page below in Chrome and click on a disabled inline edit or pager button. A rectangle will app ...

Simple server using node.js and express to host an HTML file and associated resources

I am currently experimenting with frontend development and need a basic web server to quickly start projects and serve files. Specifically, I have one index.html file along with some css/js/img files. I decided to work with Node.js and Express for this pur ...

I am interested in extracting information from the Firebase real-time database and showcasing it on my HTML webpage

I am struggling to display data from the Firebase real-time database on my HTML page. Even though I can see all the data perfectly in the console, it doesn't show up on the webpage. I attempted to use a for loop, but it still doesn't display the ...

Automating the Process of File Downloads Using Ajax and PHP

I am currently working on a form that requires users to enter a secret key. Once the key is submitted, it is verified against a database. If the key is found, the relevant file associated with the key should be downloaded automatically. I have successfully ...

Having trouble with the width of the Material-UI drawer feature

Encountering an issue with the material-ui drawer. I adjusted the width of the drawer container, which led to a problem where the drawer remains slightly inside the page and visible without clicking the button. It seems to be related to the transform attri ...

Adding an exception for ClickAwayListener in React-MUI

Hey there! I'm currently exploring MUI and trying to incorporate the ClickAwayListener API into my project, but I'm facing some difficulties. You can take a look at my project on codesandbox here: https://codesandbox.io/s/react-leaflet-icon-ma ...

Exporting SQL query data as a JSON object in PHP is proven tricky due to the inability to populate an array with the

I am a beginner in PHP and I'm trying to use the following function to fetch data from MySQL and populate an array, but I keep getting null values. function FetchBusinessData($connection, $email) { $query = "SELECT * from Business WHERE B_E ...

"Exploring Mocha and Chai: Tips for Generating a Comprehensive List of Errors in Test Cases

I am currently working on a unit test to validate a list of elements. Example: arr = [ { element : "aaa", validation : false }, { element: "bbbb", validation: true }, { element: "ccc", validation: false } While running my unit test, I encountered ...

Attempting to collapse the offcanvas menu in React Bootstrap by clicking on a link

Currently, I am utilizing a mix of React Bootstrap and React to develop a single-page application. In an attempt to make the Offcanvas menu close when clicking a link, I have experimented with various approaches. One method involved creating an inline scri ...

Troubleshooting problem with AngularJS and jQuery plugin when using links with # navigation

I have integrated a specific jquery plugin into my angularjs single page application. The primary block can be found in the following menu: http://localhost:81/website/#/portfolio This menu contains the following code block: <li> <a href=" ...

How do you retrieve an element using its tag name?

Just delving into the world of API's here. Working on a project involving loading a DIV with a bunch of links that I need to repurpose. Managed to disable the default onclick function, now trying to figure out how to save the "innerHTML" attribute of ...

Interactive Zoomable Tree with d3.js

I am looking to customize the zoomable icicle plot in d3js by incorporating my own data. Unfortunately, I am unable to locate the "readme.json" file for data modification and cannot get the graph to display on my local machine. Where can I find this elus ...

Date parsing error thrown by jQuery datepicker plugin

What could be causing the InvalidDate exception when attempting to parse the date using $.datepicker.parseDate("mm/yy","02/2008");? ...

What is the best way to execute a sequence of consecutive actions in a protractor test?

To achieve logging in, verifying, and logging out with multiple users, I decided to use a loop. I came across a helpful post that suggested forcing synchronous execution. You can find it here. Below are the scripts I implemented: it('instructor se ...

A guide on utilizing ng-repeat to iterate through array values in Views

Need help with using ng-repeat on array values within an ng-repeat in VIEWS? The second ng-repeat is not functioning properly. Here is the value of generalDocument.documents: ["14-10-2015.xls","15-10-2015.xls","16-10-2015.xls"] <div class="box-body ...

Ordering Algorithm in AJAX Grid

I have a specific requirement that I spotted on this website: Whenever a user clicks on the table header, the content should be sorted accordingly. I have successfully implemented this feature for tables with pre-set values. However, in my current scenar ...

Applying CSS classes to a custom AngularJS directive: A step-by-step guide

Need to have a CSS class called tab for the nav HTML element, which will be used as a directive: <nav tab></nav> The expected interpretation is: <nav class="tab"> <a></a> <a></a> <a></a> ...

Guide to direct express.js requests straight to 404 page

I need guidance on how to direct a request to a specific route in express.js directly to a 404 error page if the user is not authenticated. Currently, my middleware includes the following code: exports.isAuthenticated = function (req, res, next) { if ( ...

Problem with bcrypt npm installation on Mac OS X 10.9 and Node v0.10.22

Operating System Information: Mac OS X 10.9 Node version: v0.10.22 An error occurs when attempting to install the bcrypt package. Any suggestions on how to resolve this issue? Any assistance would be highly appreciated. > [email protected] install /U ...