Utilizing two map functions during object initialization

Is there a way to loop through multiple arrays and match them together when creating an object? Let's assume we have two arrays with the same amount of data. The goal is to pair each element from both arrays and assign them to properties of objects.

Here's the desired outcome:

{
  name: john,
  surname: doe,
  datasets: [{
    data: 1,
    vehicle: car,
    color: red
    },
    {
    data: 2,
    vehicle: car,
    color: blue,
    },
    {
    data: 3,
    vehicle: car,
    color: green
  }]
}

This is the code I've written so far:

function Constructor (name, surname, data, vehicle, colors) {
  this.name = name;
  this.surname = surname;
  this.data = data;
  this.vehicle = vehicle;
  this.colors = colors;

  this.person = {
    name: name,
    surname: surname,
    datasets: [{
      data: data.map(data => ({
        data,
      vehicle: vehicle,
      color: colors.map(color => ({
        color
      }))
      })),

    }]
    }

};


var testing = new Constructor ('john', 'doe', [1,2,3], 'car', ['red', 'blue', 'green']);

console.log (testing.person);

Answer №1

If you always have matching lengths for data and color, you can utilize the index in your map function as a second argument:

data.map((data, i) => ({
    data,
    vehicle: vehicle,
    color: colors[i]
  })
)

When dealing with non-matching data sets (e.g., one has more items than the other), there are various strategies you could consider.

  1. Assign a default color (if data has more items):

    data.map((data, i) => ({ 
      // ...
      color: colors[i] || "black"
    })
    
  2. Throw an error if the data sets do not align:

    if (data.length !== colors.length) throw "data length does not match color length";
    
  3. Take the shortest set of data and discard any extras:

    Array.from(
      { length: Math.min(data.length, colors.length) },
      (_, i) => ({
        data: data[i], color: colors[i], vehicle
      })
    );
    

And, undoubtedly, many more options exist!

Answer №2

Here's a unique approach you may not have considered yet. If the condition colors.length <= data.length always holds true, you can cycle through the colors using the remainder operator % in the following way:

data.map((data, i) => ({
  data,
  vehicle: vehicle,
  color: colors[i % colors.length]
})

function Constructor(name, surname, data, vehicle, colors) {
  this.name = name;
  this.surname = surname;
  this.data = data;
  this.vehicle = vehicle;
  this.colors = colors;

  this.person = {
    name: name,
    surname: surname,
    datasets: [{
      data: data.map((data, i) => ({
        data,
        vehicle: vehicle,
        color: colors[i % colors.length]
      }))
    }]
  }
}

var testing = new Constructor('john', 'doe', [1, 2, 3, 4, 5], 'car', ['red', 'blue', 'green']);

console.log(testing.person);

This implementation results in the sequence red, blue, green, red, blue when data.length === 5

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

Passing props through Link in React can be a tricky process, especially when encountering issues with undefined props like this

My latest project involves creating a recipe research tool in react. The homepage features buttons that allow me to search for recipes and view them based on the data I gather. However, when I try to access the state values using 'console.log(this.pro ...

Exploring the caching capabilities of NextJS and Vercel for optimizing simple fetch

I have successfully deployed a NextJS (13.2.4) app to Vercel after testing it locally with great results. The issue I am facing is related to a simple fetch request from a component ('use client'). This request is directed towards a route within ...

Get a jQuery object from an array

I have a challenge where I am storing jQuery elements in an array and need to retrieve them. My current approach is as follows: var arr = []; arr.push( $(someElement) ); When attempting to retrieve the element, I use: arr.indexOf($(someElement)); Unf ...

The program encountered an issue: Initialization must be completed before utilizing hooks

I'm facing an issue with my new Next app. I added line no. 6 and now I'm getting an error. Can anyone help me understand why? https://i.sstatic.net/lMKH5.png import Head from "next/head"; import Image from "next/image"; impor ...

Utilizing OrbitControls with Socket.io in a Three.js Sphere

I'm currently troubleshooting an issue with my project. I have a three.js sphere ("HTML1" on Desktop) with controls (THREE.OrbitControls) that is functioning properly on both my computer and tablet. My goal is to control this sphere through my iPad, s ...

What is the best way to highlight the option with a value of 0 by giving it a red background using either CSS, jQuery, or both, regardless of whether it is

I have tried various CSS and jQuery combinations to address the issue of displaying the option with a value of 0 in red only when it is not selected. .red { background: red; } select option[value=0] { background: red; } <select id="ups"> < ...

Master the art of line animations with D3.JS

Recently delving into D3 and I have a query regarding the animation of lines. I have been able to animate circles with the following code snippet: var data = d3.range(100).map(function() { return new agent( 0, 0, (Math.random() ...

Error: No @Directive annotation was found on the ChartComponent for Highcharts in Angular 2

I'm having trouble integrating Highcharts for Angular 2 into my project. After adding the CHART_DIRECTIVES to the directives array in @Component, I encountered the following error in my browser console: EXCEPTION: Error: Uncaught (in promise): No ...

`Javascript often returns NaN for basic calculations`

Hello, I am currently developing a basic calculator for a game but I have encountered an issue. Despite having just started learning this programming language and reading all available tutorials, I am now in the process of writing code to gain more experie ...

Displaying numbers individually with commas in a Django template

I am facing an issue where the number being typed into a text field does not have commas separating the thousands For example, if the user types 500000, it displays as 500000 instead of 500,000 This issue is present in the models section of the code: so_ ...

Searching for identical consecutive numbers in a grid

Hi there, I'm currently working on developing a function that can detect if a N*N matrix contains at least two adjacent numbers (ranging from 0 to h-1) in the up-down-left-right directions. The function should return 1 if such numbers are found, and 0 ...

Issue encountered while transforming the data buffer into the video within a Node.js environment

I am attempting to create a buffer from the mp4 video, and then convert that buffer back into the video. The buffer is being generated as follows: const buffer = Buffer.from("Cat.mp4"); console.log(buffer); The output I receive is <Buffer 43 61 74 2e ...

"Flaw discovered in Python's Lottery Program due to a logic

I have been working on a code where the user is required to input 6 'lottery' numbers ranging from 1 to 59, and the computer generates 6 random numbers within the same range. The program then needs to compare the two sets of numbers to determine ...

Retrieve the associative array from the user input by utilizing jQuery

How can I create an associative array from a form containing multiple text inputs using jQuery (or directly in JS)? Here's an example of the form: <form> <input type="text" name="name[13]" value="test 1" /> <input type="text" name="nam ...

What is the best way to fetch JSON data in React from the start and then manipulate it as needed before exporting to another file within my application?

I have a scenario where I need to fetch data from a MongoDB database using async/await fetch() and save it in a file called data.js. However, I am facing an issue with React executing "in parallel" due to the nature of async/await. This makes it difficult ...

Is it possible to permanently alter HTML values with JavaScript?

Can a html value be permanently modified using javascript? I am trying to edit a local file. Below are the codes I'm using: function switchPic(){ top.topPage.activeDef = top.topPage.document.getElementById('h1'); top.topPage.activeDef. ...

Issue encountered during rootScope update

I've encountered an issue with my Angular service that updates the $rootScope. The actual updating process works as intended, but it triggers an error in the console that has me concerned. app.service("scroll", function($rootScope, $window) { this ...

Working with AngularJS: Utilizing the Ng-repeat directive for iterating

I am struggling to figure out why the following code is not functioning properly. <div ng-repeat="r in reservations" ng-init="new = r.some_code"> <div ng-if="old == new"> <p ng-init="sum = sum + r.cost">{{r.name}} - {{r.cost}}</p&g ...

Exploring advanced routing concepts in Angular 2

I have a challenge in setting up routing in angular 2 with the following scenario home.component: @RouteConfig([ { path: '/', name: 'Home', component: HomeComponent }, { ...

Authorization based on user roles in Node.js or Express.js

Are there any modules available for implementing role-based authorization in node.js or Express js? For example, having roles such as Super Admin, Admin, Editor, and User? ...