Join multiple arrays to create an array containing objects in JavaScript

Consider the scenario where I have three arrays representing names, number of books read, and levels of awesomeness:

let names = ["Mary", "Joe", "Kenan"];
let numberOfBooks = [2, 1, 4];
let awesomenessLevel = ["pretty cool", "meh", "super-reader"];

I attempted to merge these arrays into an array of objects using .reduce(), but unfortunately, my attempts have not been successful:

    let people = [
    {
       name: "Mary",
       noOfBooks: 2,
       awesomeness: "pretty cool"
    },
    {
       name: "Joe",
       noOfBooks: 1,
       awesomeness: "meh"
    },
    {
       name: "Kenan",
       noOfBooks: 4,
       awesomeness: "super-reader"
    }
  ]

However, I was able to achieve the desired result using reduce as shown below:

let arrFinal = [];

 names.reduce(function(all, item, index) {
  arrFinal.push({
    name: item,
    noOfBooks: numberOfBooks[index],
    awesomeness: awesomenessLevel[index]
  })
}, []);

Answer №1

You can achieve this using the map method in JavaScript:

let result = names.map( (value, index) => ({
    name: names[index], 
    noOfBooks: numberOfBooks[index],
    awesomenessLevel: awesomenessLevel[index]
}));

let names = ["Mary", "Joe", "Kenan"];
let numberOfBooks = [2, 1, 4];
let awesomenessLevel = ["pretty cool", "meh", "super-reader"];

let result = names.map( (value, index) => ({
    name: names[index], 
    noOfBooks: numberOfBooks[index],
    awesomenessLevel: awesomenessLevel[index]
}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

The map function is preferred over reduce here because the number of elements in the input arrays corresponds to the number of elements needed in the output array. Using map in such cases is more intuitive.

Answer №2

Utilize the map function to establish a direct correspondence between the input arrays and the output arrays.

let individuals = names.map(function (e, i) {
    return {name:e, books:numberOfBooks[i],quality: awesomenessLevel[i]};
});

let names = ["Alice", "Bob", "Cindy"];
let numberOfBooks = [3, 5, 2];
let awesomenessLevel = ["fun reader", "avid bookworm", "casual enjoyer"];

let individuals = names.map(function (e, i) {
    return {name:e, books:numberOfBooks[i],quality: awesomenessLevel[i]};
});


console.log(individuals);

Answer №3

An innovative way to approach this is by merging multiple arrays into a single object and using the key names as properties for the resulting array of objects

let colors = ["Red", "Blue", "Green"],
    numberOfCars = [10, 5, 8],
    carTypes = ["SUV", "Sedan", "Truck"],
    combinedObject = { color: colors, quantityOfCars: numberOfCars, type: carTypes },
    mergedResult = Object.keys(combinedObject).reduce((resultArray, currentKey) =>
        (combinedObject[currentKey].forEach((value, index) =>
            (resultArray[index] = resultArray[index] || {})[currentKey] = value), resultArray), []);

console.log(mergedResult);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Ways to verify every entered word without having to click a button

My goal is to implement real-time word checking in a textarea using JavaScript/Angular. I want to validate each word as users are typing it out. What is the best approach for achieving this? ...

Unlock the Power of jQuery Hashing with the Addition of Additional Variables

Looking for a way to include an additional variable in a URL like the one above. I've experimented with different methods but I'm not certain which is the most effective. For example: Currently using JQUERY to detect the HASH value: if (window ...

Exploring the KEY attributes within a JSON dataset

In my React project, I am working on displaying specific key values from a JSON response. For example, the fieldData {DMR_5_why_who_test: "test", why: test}. My goal is to only show the bolded or key values in my output. However, my current code is not a ...

Ways to dynamically assign value to a checkbox using jquery

var sites = sites_str.split(","); $.each(sites,function(i,j) { $('.check').append("<input type=checkbox name=site_name value=sites[i]>"+sites[i] +"</br>" }) I am facing an issue when trying to retrieve the values of selected check ...

uncovering the secrets of tree shaking when using an npm package in conjunction with webpack

Imagine having an npm package where all components are exported from a single index.js file: export * from './components/A'; export * from './components/B'; Now consider another package that relies on this initial package: import {A} ...

My React application is being loaded by Express regardless of the route I access. What could be causing this issue?

I'm struggling to access the json data located at /species because express always seems to load the react app regardless of the route I use. Can someone help me identify the issue? Here is an excerpt from my server.js file: const app = require(' ...

Issues with Javascript code syntax

I have encountered an issue while creating a new literal control from code behind. I am able to add standard HTML into it successfully, however, when I try to insert <%= SomeDiv.ClientID %> into the literal control, it simply prints exactly what is i ...

Exploring the potential of a MERN stack e-commerce search bar

I recently started learning how to create a website using the MERN stack through a tutorial on Udemy. In the tutorial, they showed how to implement a search functionality in the Header.js component: <Route render={({ history }) => <Search history ...

How can I use a JavaScript function to remove an element from a PHP array?

Imagine I have a PHP session array: $_SESSION[MyItems]=Array('A'=>"Apple", 'B'=>"Brownie", 'C'="Coin")) which is utilized to showcase items on a user's visited page. I want the user to have the ability to remove o ...

The keys within a TypeScript partial object are defined with strict typing

Currently, I am utilizing Mui components along with TypeScript for creating a helper function that can generate extended variants. import { ButtonProps, ButtonPropsSizeOverrides } from "@mui/material"; declare module "@mui/material/Button&q ...

Navigating through Switch cases and If Statements with multiple arguments can be complex for beginners in the world of JavaScript

Hi there, I have a specific case that I'm struggling to find a solution for. I am using Angular with a Firebase back-end to retrieve true or false values from a variable called ref. The variable contains 4 properties with either true or false values - ...

The code is functioning properly in the output, but it does not seem to be

I have been utilizing jquery chosen to implement a specific functionality, which is successfully demonstrated in the image below within the snippet. However, upon uploading the same code to my blog on Blogger, the functionality is not working as expected. ...

Guide on converting a unique JSON structure into a JavaScript object

I've been on the hunt for a solution to this unique format challenge, but have hit a dead end so far. The issue at hand is that I'm dealing with a JSON format that doesn't play nicely with mongoDB. My goal is to convert the JSON data into a ...

Issues encountered when trying to access a POST endpoint with .NET Framework 4.6.2

I have developed a WEB API using .NET Framework 4.6.2, specifically in my AuthController where I have implemented a test endpoint that requires a parameter. Unfortunately, I am encountering issues in hitting this endpoint and receiving the following error ...

Working with nested arrays in Mongoose/Javascript: Adding an Object to an Array within another Array

I have been attempting to add an object to an array that is nested inside another Array in Mongoose. Essentially, it's like having comments for the comments. Below is the structure of my schema: const Schema = new mongoose.Schema ({ name: {type: Str ...

The argument type 'string' does not match the parameter type 'keyof Chainable' in Cypress JavaScript

Trying to incorporate a unique custom command in Cypress (commands.js file) as follows: Cypress.Commands.add("login", (email, password) => { cy.intercept('POST', '**/auth').as('login'); cy.visit(& ...

Parent method instantiating child class instance

My code includes a parent class and a child class, with the parent class containing a modify function: const modify = (data) => { const newData = data // changes newData in some way return newData } class Parent { constructor(data) { this.d ...

Choosing items while using the Orthographic camera in Three Js

Currently, I am working on an isometric level and facing issues while trying to select objects within the level. I have tried various solutions from Stackoverflow, such as this one Orthographic camera and selecting objects with raycast. However, none of t ...

Tips for deactivating trackball rotation events and triggering a custom rotation event while adjusting the rotation speed within the custom event

In an attempt to disable the trackball control rotate event and trigger a custom rotate event, I have encountered some challenges. While setting controls.enableRotate = false; works for OrbitControl, it does not completely disable the trackball control r ...

Connect main data to sub-component

Example Vue Structure: <Root> <App> <component> Main function in main.js: function() { axios.get('/app-api/call').then(function (resp, error) { _this.response = resp.data; }) ...