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

Tips for retrieving the ID value of the <li> element using JavaScript and AJAX

Here is a snippet of code I've been using to send the value of an <option>: function getXhr() { var xhr = null; if(window.XMLHttpRequest) // Firefox et autres xhr = new XMLHttpRequest(); else if(window.ActiveXObject){ // I ...

Is it possible for setInterval to trigger restarts in Apache?

Although I am not a professional coder, I have been teaching myself by experimenting with code snippets. I enjoy playing around with coding experiments as a way to gain experience. I attempted to load PHP into a div, which worked fine. However, when I tri ...

Building personalized error messages using graphql-js and express

It has come to my attention that you have the ability to create customized errors within graphql and graphql-express. https://codeburst.io/custom-errors-and-error-reporting-in-graphql-bbd398272aeb I recently implemented a custom Error feature, but it see ...

Using regular expressions in JavaScript, we can separate a paragraph into individual sentences

Hey there! I'm currently working on a project that requires extracting sentences from a paragraph using regex in JavaScript. Unfortunately, my attempts to achieve this have resulted in syntax errors as I have tried methods used in other programming la ...

develop a Java 2D array

Currently, I have a Java code set up to calculate the average of an array and it's working flawlessly. However, I am looking to make modifications so that it can handle a 2D array (Two-dimensional). import java.util.*; public class Test3{ public st ...

Error: Attempting to access the 'clipboard' property on an undefined object results in a TypeError when invoking this.$q.electron.clipboard

I'm currently working on incorporating copy to clipboard functionality into my app using Electron. This is the command I am using: methods: { copyToClipboard () { if (process.env.MODE === 'electron') { this.$q.electro ...

Is it possible to dynamically load a specific div when the page loads, relying on the

I am using JQuery SlideUp and slideDown methods to toggle the visibility of panels. How can I load or display the first record's contact information as a default? Currently, it loads blank because I set the panel's display property to none: < ...

js respond with connection

Currently, I'm utilizing a crossdomain ajax call to retrieve data from my Rails application. After implementing a method that I found and works wonderfully, I realized that Rails does not render the associated data along with it. Despite my attempts t ...

Calculate the sum of a specific column in an HTML table using JavaScript after

I have a function called CalColumnHistDEPOSITO() that I use to sum a table column as it loads from the server side into my HTML page. However, when I apply a filter, it continues to sum the entire table ignoring the filter. (function() { 'use stric ...

What causes the disappearance of CSS styles when attempting to modify the className in react js?

I am currently working on a basic react application, and I am trying to dynamically change the name of a div element using the following code snippet - <div className={'changeTab ' + (page.login ? 'leftSide' : 'rightSide')} ...

Automated browsing: identifying the difference between AJAX and iframes

During my automated requests (scheduled at specific times, without user involvement), I have noticed that xmlHttpRequest includes extra http headers. In order for the server not to be able to distinguish these requests as automated (they should appear exa ...

Is it a cookie-cutter function?

Can someone help me solve this problem: Implement the special function without relying on JavaScript's bind method, so that: var add = function(a, b) { return a + b; } var addTo = add.magic(2); var say = function(something) { return something; } ...

Using Angular JS to submit forms on a regular basis

My HTML form is set up within an Angular controller with inputs, action, and other elements already defined. The only issue I'm facing is that the form does not have a traditional submit button. Instead, there is a separate button on the page outside ...

Node.js Twitter Typeahead.js failing to retrieve suggestions

EXAMPLE CODE FOR TYPEAHEAD : <script type="text/javascript> $('input.typeahead').typeahead({ name: 'Artist', prefetch:{url: '/queryjson, ttl: '1'}, template: '<p><strong>{{firstname} ...

Using PHP for Salesforce API integration

My apologies for my lack of familiarity with salesforce API terminologies. I've recently started developing a connector to interact with salesforce, and I've hit a roadblock. I have a specific requirement where every time a new entry is added to ...

The OOP functionality in Three.JS seems to be malfunctioning, as certain elements are not being properly accessed and displayed

I've run into some issues while trying to implement OOP in my Three.js project. The original script displays three y-rotational planes, but it seems like some objects I've created aren't being called when I check the console. Can someone ple ...

Leveraging nested objects within React state

A React child cannot be an object. If you intended to render a collection of children, utilize an array Encountering the error mentioned above has left me puzzled regarding its restrictions. Below is the code where I am facing this issue. It includes an o ...

Unable to successfully transfer a document

I am looking to upload a file onto my server. Here is what I have attempted: <input (change)="uploadImage($event.target)" hidden accept="image/*" #uploadProfileImage type="file"> uploadImage(event) { const profileImage = event.files.item(0); t ...

"Enhancing Functionality: A Detailed Guide on Callback Functions in Express

Currently, I am expanding my coding skills by learning express/Node, transitioning from C and PHP/MySQL. The MDN tutorial on express has been incredibly helpful in my learning journey, making everything straightforward. Thanks to the Mozilla teaching team, ...

Is there a way to make a selected option stay selected in vue.js 2?

Here is the structure of my Vue component : <template> <select class="form-control" v-model="selected" :required @change="changeLocation"> <option :selected>Choose Province</option> <option v-for="option in o ...