Transform an array of IDs into an array of strings using a list of objects

var myIds = [3, 4, 2];

var myObj = [
    {id:1, name:'one'}, 
    {id:2, name:'two'},
    {id:3, name:'tree'},
    {id:4, name:'four'}];

// need to obtain ['tree', 'four', 'two']

var idsToNames= function(ids, objects) {
    var myNames = myIds.map(function(id){
        // transform id to name
        foreach(o in objects){
            if (i.id == id) 
                return o.name;
        }
    });
    return myNames;
}

Is this the most efficient method for converting an array of ids into an array of corresponding names?

Answer №1

To start, modify your object in the following way

var newMyObj = myObj.reduce(function(result, currentObject) {
  result[currentObject.id] = currentObject.name;
  return result;
}, {});

console.log(newMyObj);
// { '1': 'one', '2': 'two', '3': 'three', '4': 'four' }

You can alternatively create newMyObj by looping through the array myObj, like this as well

var newMyObj = {};
for (var i = 0; i < myObj.length; i += 1) {
  newMyObj[myObj[i].id] = myObj[i].name;
}

Now, you can easily iterate over myIds and retrieve values from newMyObj, like this

console.log(myIds.map(function(id) { return newMyObj[id]; }));
// [ 'three', 'four', 'two' ]

If your environment supports ECMAScript 2015's Arrow functions, this can be expressed concisely as

console.log(myIds.map((id) => newMyObj[id]));
// [ 'three', 'four', 'two' ]

By converting your original myObj to newMyObj you will achieve constant time lookup. Otherwise, you would need to loop through the myObj array for every element in the myIds, making the runtime complexity O(n*m).

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

Unable to include in an Array

I am currently working on a tutorial about arrays, but my knowledge in this area is limited. I have encountered an error message stating "operator '+=' cannot be applied to operands of type 'double[]'." I am unsure why this error is occ ...

Is it possible to create a progress bar in blue that is similar to the horizontal blue progress bar seen in Gmail when a user submits a form?

Currently, I am utilizing Bootstrap v3.3.5 on my website. In a particular situation, I have a form displayed within a Bootstrap modal dialog. The user fills in the data and submits the form. After submission, the form remains as it is until a response is ...

Emphasize the engaged menu selection when the page is refreshed

My application is a dashboard app built with React, Redux, and Antdesign. I utilized the layout provided by Ant design at https://ant.design/components/layout/. One issue I encountered is that when clicking on side menus, the active menu gets bold but upo ...

Tips on choosing a selenium element using Javascript which is assigned as an external variable

Is there a way to select an element using protractor with selenium, pulling the element from an external JSON variable? I'm having trouble understanding how to do this correctly. The code snippet below seems to be incorrect as it references $data with ...

Is there a way to focus on a specific iteration of the ngFor loop in Angular 9 using jQuery?

I'm working on a list of items inside a modal that uses *ngFor with checkboxes. The goal is to cross out the contents of an item when its checkbox is clicked. Here's the initial code using jQuery in home.component.ts: $('body').on(&apo ...

I need help with this Jquery code - trying to target an element with a specific attribute value. What am I missing here?

I am attempting to selectively add a border around the .L1Cell element where the attribute name parent is equal to Workstation. However, it appears to be applying the border to all .L1Cell elements. Here is the link to the JSFIDDLE $(document).ready(func ...

Trouble getting CSS and Javascript to bind when dynamically appending HTML elements

Attempting to dynamically bind HTML from an Angular controller SkillsApp.controller('homeController', function ($scope, $http, $q, $timeout) { $scope.getAllCategories = function () { $http({ url: "/Categories/GetAllCategories", ...

Interactive Checkbox Generated in Jquery UI Accordion Header

I need help creating an accordion with checkboxes in the headers dynamically populated from a database. I have tried using the click() function to prevent the accordion from activating when checking the checkbox, but since the accordion is generated dynami ...

Trying to replace all instances of a word in an HTML document with a <span> element, but only for <p>, <span>, and <div> tags. It shouldn't work if the parent node already contains

Here is the HTML code snippet I am working with: <div> hello world <p> the world is round <img src="domain.com/world.jpg"> </p> </div> I am looking to replace the word "world" (or any mixed case variations) with < ...

Guide on using Fetch API to send a request to a PHP file using the POST method

Hey everyone, I've recently started delving into the world of PHP and I encountered an issue while attempting to send a post request from my JavaScript file to my PHP file using the Fetch API. Upon making the request in my console, I received the foll ...

Creating a function that generates a "card" by utilizing an array of structures

I've been working on a function to create a deck of cards. However, when I try to print the content of each card's struct, it displays strange characters instead. #include <stdio.h> #include <string.h> #define DECK 52 #define RANK 8 ...

Vuetify - Best practices for managing click events with <v-btn>?

As a newcomer to vuetify and vue, I am currently trying to understand how to handle a click event on a <v-btn>. (Using vue 2.6.10 and vuetify 2.0.0) (I was surprised to find that I couldn't locate a single functioning code snippet, despite sear ...

Jquery button click event is malfunctioning after the inclusion of jquery keyboard plugin

When I try to gather user input from a textbox using jQuery keyboard.js, the functionality works perfectly fine if I exclude the virtual keyboard code. For more information on keyboard.js, you can visit: https://github.com/Mottie/Keyboard/wiki Below is t ...

Make a div with absolute positioning overflow outside of a div with relative positioning that is scrollable

I am facing an issue with two columns positioned side by side. The right column contains a tooltip that overflows to the left on hover. Both columns are scrollable and relatively positioned to allow the tooltip to follow the scroll. However, the tooltip is ...

Updating the textarea with Ajax without the need for a button click or refreshing the

I need to implement a feature where a textarea will automatically update the database without requiring the user to click on any buttons or refresh the page. The idea is that after a keyup event, there should be a 2-second countdown timer. If no additional ...

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...

Discover the nth-smallest number within a group of m arrays that are already sorted, utilizing a concept similar to finding

Is it possible to implement a general approach similar to finding the n-th value on two sorted arrays but focusing on ignoring the insignificants and adjusting the value of n in recursion? The problem of 2 sorted arrays results in a computation time of O( ...

Revamp your jQuery Ajax call by utilizing the Fetch API

Below is my attempt to convert the following jquery's AJAX call using the fetch function: const sendingData = {...} $.ajax({ url: "/api/data/getuser", type: "GET", data: sendingData , dataType: 'json', ContentType: &a ...

Retrieving JSON data every few seconds using JavaScript

I am attempting to continuously read a local JSON file in order to generate a plot. This JSON file is updated every n seconds. To accommodate for the changing file, I am using a combination of $.getJSON() and setInterval() to read the file at regular inter ...

Unable to execute the new firebase on node server

I'm currently watching this google talk. However, I am facing an issue trying to create a firebase object. Following my package.json file, I initiated with: npm install firebase --save Then proceeded with the following steps: let Firebase = requir ...