What is the best way to keep an object in an array?

I am faced with the challenge of merging two arrays and converting them into objects stored in one array.

const name = ["Amy", "Robert", "Sofie"];
const age = ["21", "28", "25"];

The desired output:

const person =[{name: 'Amy', age: '21'}, {name: 'Robert', age: '28'}, {name: 'Sofie', age: '25'}];

I am looking for a way to automate this process as my array is lengthy, making it inconvenient to type manually. Your help is appreciated. Thank you.

Answer №1

You can utilize Array.map in the following way:

const names = ["Rachel", "Michael", "Emily"];
const ages = ["30", "35", "32"];

const people = names.map((name, idx) => ({name, age: ages[idx]}));

console.log(people)

Remember that the arrays must be of equal length.
Also, use plural form when naming Arrays.

Answer №2

If the arrays are of equal length, you have the option to utilize the map function to accomplish this task.

const fruits = ["Apple", "Banana", "Orange"];
const colors = ["Red", "Yellow", "Orange"];

const fruitColorPairs = fruits.map((fruit, index) => {
  const color = colors[index];
  return { fruit: fruit, color: color };
});

console.log(fruitColorPairs);

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 there a way to acquire and set up a JS-file (excluding NPM package) directly through an NPM URL?

Is it feasible to include the URL for the "checkout.js" JavaScript file in the package.json file, rather than directly adding it to the Index.html? Please note that this is a standalone JavaScript file and not an NPM package. The purpose behind this appr ...

Decomposing a Vue.js API response into multiple variables

Utilizing vue to send http requests and store data in variables can be done like so: the api response will have the following structure: data: data: [id:1... etc] function: fetchOffers() { this.$http.get('http://127.0.0.1:8000/api/of ...

locate sibling element

<div class="videoItem"> <div class="innerVideoItem"> <a><div class="overlayBg"></div></a> <a><img class="overlayPlay"><img></a> </div> </div> <script> ...

Maintain the division's activity even after the form has been submitted by utilizing localStorage

Having trouble maintaining the visibility of a division after submitting a form via AJAX. The situation involves a search bar that accepts various inputs such as Name, ID, category, etc. Alongside the search bar is a filter with more options for advanced s ...

The React JSX checked attribute was overridden

Trying to implement a checkbox that can be selected and reset within a popup, with the ability to update on click rather than re-rendering. Initially, setting 'checked' as { checked } in UserListElement.tsx allowed normal selection of the checkb ...

Is it important to maintain the scroll to top button at a consistent height?

I am facing an issue with my button. I want the button to remain at a consistent height even when the window size is adjusted vertically. How can I ensure that the button does not move or get pushed down as the height changes? http://jsfiddle.net/ccq9cs9L ...

Ways to verify the presence of a Hash value within an array?

Below is the code snippet for my setup: project_JSON = JSON.parse teamList = Array.new project = Hash.new() project["Assignee Name"] = issue["fields"]["assignee"]["displayName"] project["Amount of Issues"] = 0 if !teamList.include?(issue["fields"]["ass ...

Stateprovider view templates in AngularJS

WikiApp.config(function config($stateProvider, $urlRouterProvider) { $stateProvider .state('revision', { url: '/wiki', views: { "main": { controller: 'ListCtrl', ...

Implementing the insertion of data using array pointers

I am currently working on a program that adds records to a basic phone book. The code I have written so far seems to have an issue - the function stops and gets stuck at declaring struct record x, causing my added record not to display properly and ultimat ...

Executing a search and replace function using a delay within a foreach loop - the ultimate guide

Below is a snippet of code where I attempt to perform find and replace within an array by searching for keys and replacing them with corresponding values. However, the expected functionality does not work as intended, leading to multiple searches for &apos ...

Utilizing AngularJS to Retrieve URL Parameters Within a Controller

I am attempting to retrieve URL parameters in my controller: Although I came across this example, I encountered an error that appears to be connected to the loading of necessary modules. app.controller('WidgetCtrl', ['$scope', '$ ...

Overwrite the JavaScript code to eradicate any flickering issues

Here are two JavaScript snippets provided. While they both perform their intended tasks, clicking on .info in the second snippet causes the classes to be added to the body as in the first snippet, resulting in unwanted flickering. Is there a way to prevent ...

Whenever I refresh my website after deployment, I encounter an empty error using the MERN stack

Here is a question I previously posted: How can I properly use the res.sendFile for my MERN APP, as I encounter an error every time I refresh, and it was resolved there. I encountered a similar issue here, even after following the same steps that worked b ...

What causes the discrepancy in results when the id() function is used on a numpy element?

I'm new to Python and recently used the code below to create an array. However, when I checked the memory location, it displayed different results for the same element of the array. I expected them to be the same but they weren't. Can you please ...

Operation on two-dimensional arrays

Can anyone help me with the correct code for this task: I need to create a new method called calculatePercentage with parameters int exam[][] int percentages[] and return type void. This method should calculate the percentages based on the values stored ...

Ambiguous limitation regarding noptr-new-declartor

Declaration of noptr-new-declarator: [ expression ] attribute-specifier-seq_opt noptr-new-declarator [ constant-expression ] attribute-specifier-seq_opt The reasoning behind using constant-expression in square brackets for the latter case of allow ...

The concept of position() is often mistaken for a function

I am currently developing a slider and have included the code below: $(document).ready(function() { // MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH var totalWidth = 0; $('.slide').each(function() { totalWidth = totalWi ...

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

What is the best way to conceal certain choices in a dropdown menu?

How can I display only the cities in Australia in a dropdown list? I have tried to find "Australia" in the options and hide everything before and after it, but I have been unsuccessful! Here is my fiddle. <select class="dropdown" id="dropdown"> ...

Is it necessary for the raycaster to be positioned within the render() function at all times?

Looking to capture the mouse double-click event's location and generate a 3D object in that spot within the scene. My understanding is that the raycaster, which is in the render() function, constantly updates the mouse location. I am interested in ha ...