Inserting arrays into objects within an array may sound like a complex task, especially when working with ng2-charts or Charts.js

Imagine having 2 distinct arrays:

var array1 = [1,1,1];
var array2 = [2,2,2];

How can a parent array be created that contains the following 2 objects?

(The goal is to insert the given arrays above into a parent array with 2 objects while also creating the objects to include the specified keys. This is necessary for compliance with the ng2-charts ChartDataSets type.)

// The desired outcome is shown below, however, only the 2 arrays above are available at this point
[
  { data : array1, label: 'some label1' },
  { data : array2, label: 'some label2' },
]

Answer №1

let arr1 = [1, 1, 1];
let arr2 = [2, 2, 2];
let newArray = [arr1, arr2].map((element, index) => {
  return {
    data: element,
    label: `new label${index+1}`
  }
});
console.log(newArray)

Answer №2

To achieve the desired array of objects, follow the statements listed below:

var array1 = [1,1,1];
var array2 = [2,2,2];
var arrayOfObjects = [];
var temporaryObject = {};
temporaryObject.data = array1;
temporaryObject.label = "test1";
arrayOfObjects.push(temporaryObject);
temporaryObject.data = array2;
temporaryObject.label = "test1";
arrayOfObjects.push(temporaryObject);

The variable "arrayOfObjects" contains the output you are looking for.

Answer №3

utilize map along with the spread operator

const array1 = [1,1,1];
const array2 = [2,2,2];

const parentArr = [
  { label: 'some label1' },
  { label: 'some label2' },
]

function updateParentArray (array) {
  return updatedArr = parentArr.map(item => {
    return {...item, data: array }
  })
}

console.log(updateParentArray(array1))
console.log(updateParentArray(array2))

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

Finding the index of a column based on a continuous sequence of values can be achieved by following these

Consider this sequence of numbers representing components on a page: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Every set of 3 numbers makes up a page, with indexing restarting for each new page. Essentially, it follo ...

Insert a fresh row into the gridview using JavaScript

I am working with a grid view where I dynamically add new rows using JavaScript. Each row in the grid view contains an image (addButton), which triggers a specific JavaScript function when clicked. function AddNewRecord(e) { debugger; var hfFirst ...

"Enhance your React project with dynamic filtering capabilities using Ant Design's Table

When attempting the code below, I encounter an error related to columns: { title: "Gruppe", dataIndex: 'group', filters: [ this.state.dropdownItems.map((item) => ({ text: item.group, value: item.group ...

An alternative method for substituting a character within a string (character array) using multiple characters in the C programming

Working with C, an unmanaged language rather than a managed one, has become somewhat unfamiliar to me. I have the task of creating a code block that scans through a character array and replaces every occurrence of '2' with 'Ba'. The cha ...

Save a document to the file system and retrieve it using Express

Can res.download() be used after writing a file to the filesystem? router.get('/exportjson', (req, res, next) => { let json = `{"@dope":[{"set":"","val":"200"}],"comment":"comment","folderType":"window"}` const file = `${__dirname}/upload-f ...

Unable to locate node module when using Npm.require

I've been attempting to utilize the Npm.require method in order to access the ldapjs module for client authentication. Unfortunately, I'm encountering the following error message: var ldap = Npm.require('ldapjs'); Error: Cannot find ...

Error in Nestjs Swagger: UnhandledPromiseRejectionWarning - The property `prototype` cannot be destructed from an 'undefined' or 'null' object

Currently, I am in the process of developing a Nestjs REST API project and need to integrate swagger. For reference, I followed this repository: https://github.com/nestjs/nest/tree/master/sample/11-swagger However, during the setup, I encountered the foll ...

Turn the image inside the div with the nth-child selector into a clickable link

I'm currently facing a challenge on my Squarespace website where I need to add individual links to various images using jQuery. The issue is that these images do not have a shared class, and unfortunately, I am limited to adding custom CSS or JavaScri ...

Can someone advise me on the best placement for a loading icon within this AJAX form?

Can someone help me with placing a loading icon in my code? I got this code from a tutorial website and I can't figure out where to put the loading icon. Please provide an example on JSFiddle or any other platform. <script language = "jav ...

Arranging elements in ascending order in Java

I've been attempting to arrange an array in ascending order, following the instructions in example 104.5. Despite carefully reviewing my code multiple times, I'm unable to identify the mistake. Below is the code snippet from my sorting class: imp ...

What is the best way to attach click handlers to a separate class?

I am facing an issue with two click events, "button-open" and "button-close". I have a button that switches from "button-open" to "button-close" on click. However, when I click it again, instead of firing the event for "button-close", it fires the event fo ...

Angular.js and D3 - The Perfect Combination for Dynamic Data Visualization!

Having some trouble creating a chart with angular.js. The chart is not appearing on the page when using rout.js, but it works fine without it. Here's my code: var myapp = angular.module('myapp', ['angularCharts']); function D3 ...

What's the best way to implement image size and type validation, specifically for .jpg and .png files, using Multer?

When using multer to receive files from the FrontEnd, I need to validate the image size to ensure it's less than 1MB. Additionally, I want to restrict the accepted file types to .jpg, .jpeg, and .png only. const multer = require("multer"); c ...

Adjust the value of a select box to the chosen option using JQuery

Could someone please assist me with this code? I am trying to adapt it for use on my mobile device with jQuery Mobile. var obj = jQuery.parseJSON(finalresult); //alert(obj); var dept = '2'; $(document).ready(function () { //$("#opsContactId ...

How can I make a div container clickable when it is wrapped around a react-router Link component?

I am facing a challenge in my react project and I have outlined the issue below. I have enclosed all components with react-router Link. There are certain sections of code where I require the Link for navigation purposes, but there are also instances where ...

Is it possible for me to remove the style using getAttribute?

Recently, I have been working on developing a drag and drop game where the goal is to set the original value to none once the items are dropped correctly. function dragStart(ev) { ev.dataTransfer.setData("Text", ev.target.id); } function allowDrop( ...

Dynamically generating a multidimensional array on a global scale using Java

After successfully creating and implementing the web version of my Ordering System, I am now working on transferring user selections from an App to a Global Multidimensional Array for database storage. The Ordering System involves multiple steps before da ...

Update the select tag to display as radio buttons

Hey there, I've got a webpage where users can rate different systems. I've written a JavaScript function to dynamically add and remove systems for evaluation. The only issue is that I have to manually change the radio button names to prevent th ...

Assign an id attribute in KineticJS once the ajax call is successful

I have implemented KineticJS into my MVC application. To retrieve data from the database, I am utilizing ajax calls to web services in the API controller. One of the APIs returns an id that I want to assign to the current Kinetic.Group id attribute upon s ...

obtain the position of an element within an array

After entering a value in the input field, an array is generated with a length based on that input. For example, if I enter 3 in the input field, I will have var input = 3 and var sir = [0,1,2]. Can someone please help me figure out why my attempt to find ...