How to assign key-value pairs to two arrays in JavaScript?

Looking to convert two arrays into an object in JavaScript

let ar1 = ['jhon', 'doe', 'alex'];
let ar2 = ['21', '22', '35'];

The desired output should be:

obj=[
{name:'jhon',age:'21'},
{name:'doe', age:'22'},
{name:'alex', age:'35'}
]

Any tips on how to achieve this conversion?

Answer №1

To utilize the map method:

let arr1 = ["john", "doe", "alex"];
let arr2 = ["21", "22", "35"];

const newObject = arr1.map((item, index) => {
  return {
   name: item,
   age: arr2[index]
  }
})

In order to streamline the code within the map function, you can use an implicit return like so:

const newObj = arr1.map((item, index) => ({
  name: item,
  age: arr2[index]
 })
)

Answer №2

To implement this, you simply need to utilize the map function as demonstrated in the following example:

    var names = ["Alice", "Bob", "Charlie"];;
    var ages = ["25", "30", "22"];

    var combinedInfo = names.map(function(name, index) {
        return {person: name, age: ages[index]};
    });

Answer №3

   names = ["jhon", "doe", "alex"];
   ages = ["21", "22", "35"];
let createObject = function createObj(names,ages){let objects = []; names.map((item,index) => {let obj ={};obj['name']=item; obj['age']=ages[index];objects.push(obj);}); console.log(objects);return objects;}(names,ages);

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

Encountering Error 5 while trying to execute JavaScript code in Sublime Text

After successfully integrating a JavaScript console into Sublime Text 3 using node.js, I encountered some issues that required troubleshooting. The build code (saved as Node.sublime-build) looked like this: { "cmd": ["node /Program Files/nodejs", "$file" ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...

Transferring information between two separate components

Hey there, I'm struggling with the Payment Component. What I want to achieve is that when I click on a link, it transfers (ClassG, imageG, and PriceG) to the Payment Component where I can then style them accordingly. I've attempted something, but ...

How about this: "Looking to Share on Social Media with ME

After developing an app using MEAN.js, I made enhancements to the Articles (blog) section to improve SEO, readability, and design. However, one issue I'm struggling with is how to properly share these Articles on social media platforms like Facebook, ...

Loading components dynamically with axios is a valuable feature

Can this be achieved? There is a spinner component. axios: action() { SPINNER (component) -- activate axios.get('/store', { params: { something } }) .then ((resp) => { SPINNER (component) -- ...

Tips for implementing custom fonts in NextJS without relying on external services

Utilizing Fonts in NextJS I have been researching various methods for using self-hosted fonts with NextJS. When attempting the following code, I encountered a [ wait ] compiling ...: @font-face { font-family: 'montserrat'; src: url(&a ...

Ways to increase the shrinking capacity of flex items when the entire container width is occupied

Recent Post Below: I've replicated a minimized issue: https://codepen.io/MH-123/pen/ExJWQWq?editors=1100 In the provided CodePen, the problem persists. Two divs are present, but flex shrink functionality is not working as expected. The main flex cont ...

When using .map() to iterate through an array of objects in Next.js, why does the data display in the console but

I'm facing an issue with displaying the elements of an array in HTML. I'm fetching data from the Bscscan API and while I can retrieve data successfully from the first API, the second one doesn't display the data in the local browser. I' ...

Is it acceptable to display a collection of components in React 16?

A colleague recently mentioned to me that rendering an array of components in React 16 is frowned upon. Is this true? Can anyone provide insight on this matter? ...

Invoking a prototype method executes the incorrect function repeatedly

I'm currently diving into the world of structures and anonymous functions in JavaScript, and after examining various codes and libraries that implement this technique, I decided to give it a shot. However, when attempting to replicate the method they ...

What is the process for creating a list using layers that are published in Geoserver?

I am currently working on developing a webmapping application. One of the tasks I need to accomplish is parsing the WMS request in order to retrieve the title of each layer within the layers section: var xhr = new XMLHttpRequest(); xhr.open(' ...

Troubleshooting problem with Angular2's Json.parse(--) functionality

Here is the issue related to "JSON.parse(--)" that you need to address: ERROR in E:/Arkin_Angular_Material_latestCode/arkin-layout/src/app/core/service/ http.service.ts (62,53): Argument of type 'void | any[]' is not assignable to parame ...

Modify the row's background color after clicking the delete button with jquery

Greetings, I am facing an issue with changing the color of a row in a table when clicking on a delete button. Despite trying various methods, I have not been successful. How can I modify the ConfirmBox() method to change the row's color? Your assistan ...

A step-by-step guide on changing an image

Is it possible to change an image when the user clicks on a link to expand its content? <ul class="accor"> <li> Item 1 <img src="../plus.png"> <p> Lorem ipsum dolor sit amet</p> </li> </ul> $(' ...

Ensuring that only one field is selected with mandatory values using Joi validation

Is there a way to create a validation rule utilizing Joi that ensures if valueA is empty, then valueB must have a value, and vice versa? My current approach involves using Joi for validating an array of objects with properties valueA and valueB. Below is ...

When ran automatically as a cron job, the JavaScript script fails to establish a connection with MongoDB

As I connect to mongodb (on a Ubuntu machine) from a js script, everything runs smoothly when I execute the command from the command line (node <name of the script>). However, when I try executing the same command from cron, the connection times out: ...

Looking to show an image when a checkbox is ticked and hide it when it is unticked in HTML?

How do I make a specific image appear when a user clicks on a checkbox? I'm unsure if I should use jQuery, Ajax, or another method. What is the best approach for this task? Your assistance would be greatly appreciated. I have successfully created the ...

Check to see if the user has been redirected to the page using JavaScript

When a file input validation fails in a Laravel project, the user is redirected back to the current page. However, the issue arises when the user has to scroll down to see the error message and understand what went wrong. This doesn't provide the bes ...

Service Worker in Workbox with Background Sync functionality

For the past few days, I have been utilizing Workbox and ensuring that I am setting it up correctly to generate a service worker from a source instead of letting Workbox do it for me. While everything seemed to be working fine, I recently attempted to int ...

problem with the visibility of elements in my HTML CSS project

How do I prevent background images from showing when hovering over squares to reveal visible images using CSS? h1 { text-align: center; } .floating-box { float: left; border: 1px solid black; width: 300px; height: 300px; margin: 0px; } div ...