Adding text in a key value pair object can be easily achieved by specifying the key

I was able to transform two arrays into a key-value pair object.

firstArray: [] = ['a','b','c','d']
secondArray: [] = [1,2,3,4]

Below is the code used to accomplish this transformation:

let dict = firstArray.map(function(obj, index) {
let mydict = {}
mydict[secondArray[index]] = obj;
return mydict;
});

console.log(dict) 
Output: 
 [{
  "1": "a"
}, {
  "2": "b"
}, {
  "3": "c"
}, {
  "4": "d"
}] 

The expected output from this transformation is as follows:

[{
 value: "1", name: "a"
}, {
value:  "2", name: "b"
}, {
value:  "3",name: "c"
}, {
 value: "4", name:"d"
}]

If anyone can provide guidance on how to achieve this desired output, it would be greatly appreciated.

Answer №1

const animals = ['dog','cat','bird','fish'];
const numbers = [5,10,15,20];

const dictionary = animals.map((item, idx) => {
   return {
    value: numbers[idx].toString(),
    name: item
   };     
});
console.log(dictionary);

Answer №2

I believe it is feasible to achieve this.

let x = ['apple','banana','cherry','date'];
let y = [1,2,3,4];
let newArray = [];
for(let j = 0;j<x.length;j++){
    
    let tempValue = {
        'type' : y[j],
        'label' : x[j]
    }
    newArray.push(tempValue)
}
console.log(newArray);

Given the fixed indices of the data, utilizing them for operations is viable, and alternative looping methods can also be employed.

Answer №3

Here is a code snippet that demonstrates how you can map two arrays together:

const firstArray = ['apple', 'banana', 'cherry'];
const secondArray = [10, 20, 30];

const result = firstArray.map((fruit, index) => ({
  name: fruit,
  quantity: secondArray[index].toString()
}))

console.log(result)

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

Create a hierarchical dictionary structure by nesting dictionaries containing child elements from an array

Let's say I have fetched an array of dicts from a web API. Each dict contains keys like name, description, 'parent', and children. The children key consists of an array of dicts. Here is a hypothetical example for better understanding: [ ...

Retrieving data from Firebase in an asynchronous manner

I am currently working on a business management web application using React with Firebase for the backend. I have also implemented a local API to simplify some of the Firebase functions. One of the methods I created is designed to retrieve data from a spec ...

Steps for eliminating an item from an array in MongoDB

I have been struggling with the functionality of the Mongoose library, specifically the remove method. On my webpage, I display comments and have a form with a Delete button. My objective is to delete only the comment that was clicked. Below is an excerpt ...

The overall outcome determined by the score in JavaScript

Currently, I am working with a dataset where each person is matched with specific shopping items they have purchased. For instance, Joe bought Apples and Grapes. To gather this information, individuals need to indicate whether they have made a purchase. I ...

Searching for NavigationEnd events specifically in Angular 12?

When using Angular 11, the following code snippet functions correctly: this.r.events.pipe( filter(event => event instanceof NavigationEnd), map((event: NavigationEnd) => event.url == ROUTES.APPLICATION)) However, when migrating to Angular 12 ...

Implementing a Searchable Autocomplete Feature within a Popover Component

Having an issue saving the search query state. https://i.stack.imgur.com/HPfhD.png https://i.stack.imgur.com/HbdYo.png The problem arises when the popover is focused, the searchString starts with undefined (shown as the second undefined value in the ima ...

Using Typescript to define classes without a constructor function

As I was going through the "Tour of Heroes" guide on the Angular website, I came across the following code snippet: class Hero { id: number, name: string, } const aHero: Hero = { id: 1, name: 'Superman' } console.log(aHero instanceof H ...

define a function with default arguments and a callback

When working with a JavaScript library, I encountered an issue where I needed to define my callback functions within an object. The goal was to include default parameters in the arguments of these callback functions stored in a TypeScript object. Here is a ...

Having trouble implementing the latest Angular Library release

Just starting out with publishing Angular libraries, I've made my first attempt to publish a lib on NPM called wps-ng https://www.npmjs.com/package/wps-ng. You can check out my Public API file here https://github.com/singkara/wps-js-ng/blob/library_t ...

Removing White Spaces in a String Using JavaScript Manually

I have created my own algorithm to achieve the same outcome as this function: var string= string.split(' ').join(''); For example, if I input the String: Hello how are you, it should become Hellohowareyou My approach avoids using ...

Why is Angular ng-block-ui not functioning properly in Angular 7?

Within my app.module.ts file import { BlockUIModule } from 'ng-block-ui'; imports: [ BrowserModule, BlockUIModule.forRoot(), ] Inside the dashboard component: import { BlockUI, NgBlockUI } from 'ng-block-ui'; export class Da ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

Concerns with combining key value pairs in Typescript Enums

Could you help me figure out how to properly implement an enum in my drop-down so that I can only display one value at a time? Currently, I am seeing both the key and the value in the list. This is my enum: export enum VMRole { "Kubemaster" = 0, "Kub ...

What is preventing this PHP script from functioning properly with Google Maps?

I'm having trouble understanding why this PHP script isn't generating the specified map on the HTML page. Any suggestions? <!doctype html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-sc ...

Scraping a few URLs with Javascript for Web Data Extraction

I'm struggling to retrieve data from multiple URLs and write it to a CSV file. The problem I'm facing is that the fetched data is not complete (I expect 10 items) and it's not in the correct order. Instead of getting 1, 2, 3 sequentially, I ...

What is the best way to determine the midpoint index of an array?

As a newcomer, I have a question regarding a recent assignment. The task involves creating a global array where objects are imported as they are entered into an input field on the HTML document. The challenge is to update the current list on the document ...

Tips for inserting a DIV and SCRIPT from a single HTML template into a webpage

I'm working with an HTML template that contains a DIV with a button and a script with a function to call when the button is clicked: <div id="CLC_Form"> various text and checkbox inputs go here... <br> <input type="button" ...

Run a script tag prior to displaying the modal

Currently, I am attempting to display a bootstrap modal with dynamic content. One of the values being passed to the modal is the HTML that should appear inside it. The issue I am facing is that within the HTML content being passed, there is a script tag t ...

Retrieving data from AJAX requests

I have an AJAX code that sends data to the server and returns results including id, name, and quantity. How can I extract and print only the quantity, id, or name? Thank you for your help! <script type="text/javascript"> $("#bto_update_quan ...

Issue: Failed to access the 'setDir' property of an undefined object

Greetings, I am a newcomer to Ionic/Angular and have been facing a particular issue for over 20 days now. I have created a small app and would like to implement multi-language support with both RTL and LTR directions. I followed the documentation provided ...