Generating an array of objects with various attributes in JavaScript

Is there a way to efficiently create an array of objects with properties for "name" and "shade"?

[{
    "name": "black",
    "shade": "dark"
  }, {
    "name": "white",
    "shade": "light"
  },
  {
    "name": "red",
    "shade": "dark"
  }, {
    "name": "blue",
    "shade": "dark"
  },
  {
    "name": "yellow",
    "shade": "light"
  }]

Currently, I have two separate arrays:

name = ["black","white","red","blue","yellow"]
shade = ["dark","light","dark","dark","light"]

What are the steps needed to combine these arrays into one cohesive object array structure?

Answer №1

Utilize the map function.

let result = names.map( (name, index) => ({ name: name, color: colors[index] }) );

Example

const names = ["black","white","red","blue","yellow"];

const colors = ["dark","light","dark","dark","light"];

let result = names.map( (name, index) => ({ name: name, color: colors[index] }) );

console.log(result);

Answer №2

let combined_arrays = [];
// ensuring the arrays are of equal length
for (let j = 0; j < colors.length; j++)
    combined_arrays.push({color: colors[j], tone: tones[j]});

Answer №3

You could utilize the .map() method for this task:

let colors = ["green", "purple", "orange", "pink", "turquoise"],
    tones = ["deep", "pastel", "vibrant", "soft", "bright"];

let combine = (arr1, arr2) => colors.map((color, index) => ({color: color, tone: tones[index]}));

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

Answer №4

One way to simplify handling various types is by using a helper object.

var colors = [ "red", "green", "blue", "yellow"],
    shades = ["dark", "light", "dark", "dark", "light"],
    data = { color: colors, shade: shades },
    processedData = Object
        .keys(data)
        .reduce(
            (result, key) => (data[key].forEach((value, index) => (result[index] = result[index] || {})[key] = value), result),
            []
        );

console.log(processedData);
.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

observing which specific element corresponds to the nth child?

Exploring the concept illustrated in https://api.jquery.com/eq/, imagine a scenario with the following HTML structure: <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item ...

Combine table cells to improve readability on smaller screens

I currently have a setup designed for larger screens: <table> <thead> <tr> <th>title and image</th> <th>description</th> </tr> </thead> <tbody> ...

What is the reason I am unable to both declare and define a char-pointer variable that points to a char-array?

What's the issue with initializing s2 in the code snippet below? #include <stdio.h> int main() { char *s1 = "foo"; char *s2 = {'f', 'o', 'o', '\0'}; printf("%c\n", s1[1]); printf("%c&b ...

"Unleashing the power of Asynchronous Ajax Operations

$("#container").on("change", "#control1", function() { if ($("#checkData").val()) { $.get("/Controller/CheckData/" + $("#control2").val(), function(data1) { if(!data1.Success) { alert("Unable to do POST."); ...

Adjust the image to stretch and crop appropriately to perfectly fit the specified dimensions

I have a div with an image inside of it, and the overflow of the div is set to hidden so that the image will be cropped if it exceeds the width or height. It was working correctly, but sometimes it doesn't. What could be causing this issue? Here is th ...

Creating a dynamic form in my functional component is essential as it allows for seamless generation based on the specific data received. The variations in data directly correspond

When working with the code below, I receive an Object as input. From this object, I extract specific keys to use as labels for a form. I have implemented various for loops that can generate an array of const variables. However, my challenge lies in const ...

Unable to send a POST request to http://localhost:5000/api/createuser

During my journey through a MERN stack project tutorial on YouTube, I've come across a roadblock in the middle of my progress. The issue at hand involves the incorporation of user registration, which is a recent addition to my project. Utilizing Thund ...

The buffer for the operation `users.insertOne()` exceeded the timeout limit of 10000 milliseconds, resulting in a Mongoose

I am currently utilizing a generator that can be found at this Github link Project repository: Github Project Link Encountering an issue when attempting to input a user using the `MASTER_KEY`, I keep receiving the following error message: MongooseError ...

Warning in React js: [eslint] srcApp.js Line 2:8 - The variable 'person' is declared but not utilized

[![I need assistance with this problem. Whenever I try to resolve it, I consistently encounter the same error on Line 2:8: 'person' is defined but never used - no-unused-vars.][1]][1] ...

Displaying various elements with distinct properties in React using ES6

<---------------------MODIFICATION------------------------> I initially thought I needed multiple onChange functions, but after reviewing the answers provided, I discovered a solution thanks to the helpful user's response. With some experimenta ...

Exploring the depths of JavaScript JSON elements

After processing my PHP code, it generates a JSON output that contains multiple entries in the same structure. Here is an example with two entries: { "0": { "campaign_id": "31", "title": "new title", "description": "new descrip ...

Navigating a path and executing unique functions based on varying URLs: A guide

I am trying to send a post request to the path /users and then right away send another post request to /users/:id. However, I need the actions to be different for each of these URLs, so I cannot use the array method to apply the same middleware. The goal ...

determining the size of a character array

Can someone help me understand why I am getting results of 6 and then 8 from the code below? I've looked through various posts but haven't found an exact match for my question. Thank you in advance. #include <stdio.h> void getSize(const c ...

Which programming language should I utilize to create a webpage that dynamically updates its content from a database?

Seeking advice on a complex task I'm facing. I'm currently managing a vast spreadsheet (266 rows with 70 columns, and growing) which serves as a database. I want to transfer this data from Excel to an intranet page. Currently, I'm using a mi ...

Beware: Inaccessible code detected in Reactjs usage

Currently, I am working on a ReactJS project where I have integrated two components - PrescriptionIndex and PrescriptionNew. Let's start with the 'PrescriptionNew' component: import React, { Component } from 'react'; import Flo ...

Obtaining verified user information through Express using a JWT token

Having recently ventured into Express, I have prior experience with Laravel and PHP. Currently, my concern lies with a database schema structured like this: Users table : created_by updated_by In Laravel, I could easily auto-fill the 'created_by&ap ...

What is the best way to insert a variable URL in JavaScript code?

When working with PHP, I often create a declaration similar to the following (taken from an example on Stack Overflow): <script type="text/javascript"> var templateurl = "<?php bloginfo('template_url') ?>"; </script> Subse ...

What is the process for retrieving the width value from an input field using jQuery?

This example demonstrates an alert trigger when the input value width or cursor crosses the input width. How can we retrieve the width of the input value without just getting the length of the value in jQuery? $('.value_width').text($('.i ...

What are the best techniques for showcasing rich text content in vue.js?

I'm working on a web application and attempting to showcase uploaded rich text content using vue.js. The content is generated by Action Text in the following format. <h1>text</h1><div>sample text<br><action-text-attachment ...

The JSON file overwrites entire objects instead of targeting individual ones

Is there a way to update just one specific object in a JSON file without affecting the rest? I've implemented a put request on the front-end using axios to send data to the back-end for processing. However, the current functionality replaces all obje ...