Combining two arrays of names and values into a fresh object using Javascript

Trying to merge two arrays, one for column headers:

cNames = ["Year","Count"]

And another for data:

mData  = ["2005",50212,"2006",51520,"2007",52220,"2008",52143]

The goal is to combine them like this:

[
    {
        Year: "2005",
        Count: 50212
    },
    {
        Year: "2006",
        Count: 51520
    },
    {
        Year: "2007",
        Count: 52220
    },
    {
        Year: "2008",
        Count: 52143
    }
]

Tried to achieve this with:

var data;
for (var i=0; i < mData.length; i++) {
    for (var j=0; j < cNames.length; j++) {
        data[cNames[j]]=mData[i];
    }
}

. . . but the output was not as expected. Any suggestions on how to fix this would be greatly appreciated!

Answer №1

To dynamically push elements to an array based on the length of the key array, you can use the reduce method in JavaScript. This approach allows for working with arrays of any size, as long as the keys and values align properly.

var cNames = ["Year","Count"]
var mData  = ["2005",50212,"2006",51520,"2007",52220,"2008",52143]

var arr = mData.reduce( (a,b,i) => {
  if (i%cNames.length === 0) 
    a.push(mData.slice(i,cNames.length+i).reduce((c,d,j) => (c[cNames[j]] = d, c),{}));
  return a;
}, []);

console.log(arr)

Answer №2

Here is a step-by-step guide on how to accomplish this task

const labels = ["Year", "Count"];
const data = ["2005", 50212, "2006", 51520, "2007", 52220, "2008", 52143];

let index = 0;
let finalResult = [];
while(index < data.length){
    let temporaryObject = {};
    for(let j=0; j<labels.length; j++){
        temporaryObject[labels[j]] = data[index+j];
    }
    finalResult.push(temporaryObject);
    index += labels.length;
}
console.log(finalResult);

Answer №3

Or perhaps we can try a different method :)

var categories = ["Year","Count"];
var data  = ["2005",50212,"2006",51520,"2007",52220,"2008",52143];

var result = [];
for (var i = 0; i < data.length; i+=categories.length) {
  var object = {};
  for (var j = 0; j < categories.length; j++) {
    object[categories[j]] = data[i + j];
  }
  
  result.push(object);
}

console.log(result);

Answer №4

Check out this code snippet that performs the task

cNames = ["Type","Quantity"];
mData  = ["Apple",50,"Banana",25,"Orange",30,"Grapes",40];

var combinedData = [];
var i = 0;
mData.forEach(function(value,index){
 if(i%2==0)
 {
   var itemToPush = {};
   itemToPush[cNames[0]] = value;
   itemToPush[cNames[1]] = mData[index + 1];
   combinedData.push(itemToPush);
 }
 i++;
});

console.log(combinedData);

Answer №5

let categories = ["Year","Count"];
let mainData  = ["2005",50212,"2006",51520,"2007",52220,"2008",52143];

let newData = [];
let numOfCategories = categories.length; 

while(mainData.length > 0)
  {
  let values = mainData.splice(0,numOfCategories);
  let tempObj = {};
  for(let j=0; j<numOfCategories; j++) tempObj[categories[j]] = values[j];
  newData.push(tempObj);
  }

console.log(JSON.stringify(newData));

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

The JSColor onChange event is throwing an error indicating that the function is not defined

When attempting to use the onChange event for JSColor to call a function, I consistently encounter an error indicating that the function is not defined. The code snippet below illustrates the issue: export class NavBar extends React.Component { constr ...

Utilize Vue.js to transmit HTTP requests with specified headers and parameters

I'm trying to figure out how to create a LinkedIn login component, but I'm having trouble finding information about headers and parameters. Can someone help me understand how to send a GET or POST request with parameters and headers? Here's ...

Execute a JavaScript function prior to initiating an AJAX request

To streamline the process of making AJAX calls in my .NET project, I have developed a function called checkConnection that checks for internet connectivity before each call. However, currently, I am manually calling this function on every button click that ...

The variable is unable to be accessed within the PHP function query

After passing a variable through ajax to a function within my php file "Cart_code.php", I encountered an issue where the variable was not accessible inside the function. Can you help me figure out why? Javascript $.ajax({ type: "POST", url: "incl ...

Exploring the functionalities of Express and Socket.io

I am new to creating a Node.js app using express V 3.4.8 and socket.io V 0.9.16 to display a map with markers showing where users are connecting to the site. I am doing this to learn more about node.js and how to incorporate maps into my projects. However, ...

Using jQuery to retrieve the values of two distinct sliders and executing a specific mathematical operation

I have two sliders with their own values and properties: https://i.stack.imgur.com/3OZqr.gif My goal is to retrieve the values of these two sliders and calculate a result that will be displayed next to the interest label. The calculation formula is: poun ...

Updating contact list to a database table structure

Currently, my code displays the data in address books, but I would like it to be shown in a table instead. I attempted to use document.write to create the table, but I'm unsure how to populate the table with the data rather than the address book forma ...

Will the rel attribute work in all web browsers and with all HTML tags?

Confirming that it is compatible for use with JQuery scripting. ...

Identifying modifications in json file within Ansible can be problematic when using jq due to variations in indentation, resulting in the file always being marked as

Looking to use Ansible to update a specific string in a JSON file? Unfortunately, Ansible lacks a module similar to xml for handling JSON files. As a workaround, I'm utilizing the jq command-line tool. Since restarting the application is time-consumin ...

The function toJson() does not exist for the specified stdClass object

After following a tutorial on implementing websockets in Laravel to create a live commenting system, I encountered an error that I cannot figure out. Even though I followed the code exactly as demonstrated in the video, this error persists. Does anyone hav ...

The current status of an ASP.Net Mvc Ajax request

Currently, I am utilizing @Ajax.ActionLink to invoke a controller action in an ajax manner. Is there a method to identify if there is already an ongoing/pending ajax request on the page? The desired functionality is simple: when a user clicks the link, the ...

Fixing blurry text on canvas caused by Arbor.js mouse event issues

Currently, I am utilizing arborjs in my project. The text within the canvas is created using fillText in html5. While everything functions correctly on a Retina display MacBook, the text appears blurry. To address this, I applied the following solution: v ...

When clicked, elevate the element to the top of the window with an offset

Is there a way to click on this button, which is located within an accordion section header, and have it automatically move to the top of the page based on the window size? It seems like it should be a simple task, but sometimes after a long day things ca ...

Introducing a fresh parameter to initiate and end Server Sent Events

Assistance needed. I have implemented Server Sent Events to dynamically update a website using data from a database. Now, I aim to send a new parameter ('abc.php/?lastID=xxx') back to the PHP script based on information received in the previous ...

Performing optimized searches in Redis

In the process of creating a wallet app, I have incorporated redis for storing the current wallet balance of each user. Recently, I was tasked with finding a method to retrieve the total sum of all users' balances within the application. Since this in ...

Role Based Routing in React allows for different paths and components

I am currently working on a project involving React and I need to implement different routes for admin and driver roles. I have two separate route objects for each role's claims. I am retrieving the user's role from an API and I want to display t ...

The DELETE request in my app using React Native and Fetch API is experiencing difficulties, although it is successfully working when tested in

We are facing an issue with our API while querying through React Native. Surprisingly, GET and POST requests work perfectly fine in both our app and Postman. However, the DELETE functionality seems to be failing on the app, even though the same request w ...

Creating an attractive image carousel using jQuery or YUI for your website

I am searching for a javascript-based slideshow solution for images. I have received the following requirements: The slideshow should fade one image into another, looping back to the first image after all images have been displayed It must include naviga ...

The issue of excessive recursion in Typescript

Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions. About ...

Creating dynamic cubes in Magento with interact.js within a .phtml template

I utilized the interact.js library to create this code snippet, which functions perfectly on Chrome, Firefox, and w3schools "Try it Yourself" platform (unfortunately not compatible with Edge and IE for unknown reasons). However, when I include this code wi ...