What is the process for dynamically inserting values into an array of objects using Javascript?

Below is a collection of objects:

var items = [
      {"label" : "1", "value" : 12},
      {"label" : "2", "value" : 15},
      {"label" : "3", "value" : 20},
      {"label" : "4", "value" : 25}
    ];

I am looking for a way to dynamically add values to this array. I attempted the code below without success:

var labels =["1","2","3", "4"];
var values = [42,55,51,22];
var newData = new Array();
for(var i=0; i<4; i++){
   newData[i].label = labels[i];
   newData[i].value = values[i];    
}

Answer â„–1

If you want to use the object, you have to first instantiate it. A simple way to do this is shown below:

var languages =["JavaScript","Python","Java"];
var users = [100,200,150,300];
var info = [];
for(var i=0; i<4; i++)  {
    info.push({language: languages[i], userCount: users[i]});
}

Alternatively, you can achieve the same result, but in a less concise manner that resembles your original code:

for(var i=0; i<4; i++)  {
   info[i] = {};              // creates a new object
   info[i].language = languages[i];
   info[i].userCount = users[i];    
}

array() will not create a new array (unless you defined that function). Use either Array(), new Array(), or simply [].

I suggest reading through the MDN JavaScript Guide for a deeper understanding.

Answer â„–2

During the year 2019, an efficient and concise method to achieve this task is by utilizing Javascript's ES6 Spread syntax.

data = [...data, {"label": 2, "value": 13}]

Illustrative Examples

var data = [
      {"label" : "1", "value" : 12},
      {"label" : "1", "value" : 12},
      {"label" : "1", "value" : 12},
    ];
    
data = [...data, {"label" : "2", "value" : 14}] 
console.log(data)

In your specific scenario (even though it pertains to 2011), similar outcomes can be achieved using map() & forEach() as shown below

var lab = ["1","2","3","4"];
var val = [42,55,51,22];

//Using forEach()
var data = [];
val.forEach((v,i) => 
   data= [...data, {"label": lab[i], "value":v}]
)

//Using map()
var dataMap = val.map((v,i) => 
 ({"label": lab[i], "value":v})
)

console.log('data: ', data);
console.log('dataMap : ', dataMap);

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

Unable to correctly declare and display UTF-8 character within JSON syntax

In my JSON object, there is an attribute that contains a unique special character - I've attempted to save the string in encoded UTF-8 as "\xF0\x9F\x94\x94" or tried displaying it using its HEX value - String.fromCharCode(0x1F514 ...

What is the best way to code a JavaScript function that changes the labels on a mat-slider when using a range

As a newcomer, I am currently working with a mat-slider and trying to modify the label based on the range selected. However, I'm unsure how to write JavaScript code for different labels. Can anyone provide me with assistance? Here is the mat-slider th ...

Tips for aligning a dropdown button with the other elements in your navbar

I followed the code outline from a tutorial on We3schools, but I'm having an issue with the button not aligning correctly with the navbar. https://i.sstatic.net/fSRIT.png I attempted to adjust the code for proper alignment before publishing, but was ...

"The combination of Node.js, Express, and Angular is causing a continuous loop in the controller when a route is

Currently, I am utilizing node js alongside Express. Angular js files are being loaded through index.html. The code for app.js is as follows: app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); ...

Performing array multiplication by utilizing partial products in the Java programming language

I have been working on a program to store results in a 2D array, print them out in partial products, and then sum them up. However, I'm struggling with this task as I am new to programming. public class ArrayMultiplication { public st ...

What methods do current web browsers utilize to implement the JS Array, particularly when it comes to adding

When using the .push() method on an Array object in JavaScript, the underlying "array" capacity increases as more elements are added. If anyone knows of a reliable resource for this type of information regarding JavaScript, please feel free to share. upda ...

Is it possible to generate an array of strings from the keys of a type or interface?

Imagine a scenario where we have a type or interface defined as NumberLookupCriteria: type NumberLookupCriteria = { dialCode: string; phoneNumber: string; } or interface NumberLookupCriteria { dialCode: string; phoneNumber: string; } Is there a w ...

Issue with Vue-Validator form validation not functioning properly on JS Fiddle

I'm having trouble with vue-validator on JSFiddle. Can someone please assist in troubleshooting the issue so I can proceed with my main question? Check out JSFiddle Html: <div id="app"> <validator name="instanceForm"> & ...

What is the proper method for triggering an animation using an IF statement with A-Frame animation mixer?

I am currently exploring the capabilities of the animation mixer in A-Frame and trying to trigger a specific action when a particular animation is playing (like Animation 'B' out of A, B, C). Although I'm not well-versed in Javascript, I ha ...

Determine the day of the month based on a given date

My calendar date is in the format "Wed Jun 05 2013 00:00:00 GMT+0100 (CET)", but I need it to be in the yyyy-mm-dd format. Here’s what I’ve tried: var year = mydate.getFullYear(); var month = mydate.getMonth(); var day = mydate.getDay(); Unfortunate ...

Tips for indicating when the password confirmation field <input type="password">ConfirmationPassword</input> is considered valid, which occurs when it matches the original password input

I've hit a roadblock here. I just can't figure out how to manipulate JS and bypass validation. I want to trigger this - onkeyup when <input2 pwd> matches <input pwd> .l_input:valid + span::after { position: absolute; content: 'â ...

Combining two ordered arrays using a for loop

I have implemented a function that merges two sorted arrays into one and returns a pointer to the merged array. I would like to use a for loop instead of a while loop for this task. However, in some test cases, the last 1 or 2 elements of the resulting m ...

Every time an npm installation is attempted, the following error occurs: "npm ERR! Cannot read property 'resolve' of undefined."

Welcome Everyone! Currently, I am facing an issue on my dual boot system where Node and NPM were functioning smoothly on Windows 7. However, now that Windows 7 is not booting up, presumably due to hardware problems, I have resorted to using Windows 10. E ...

Ways to define two ng-change functions simultaneously

I am currently working on implementing the phonechange and emailchange functions simultaneously. My goal is to trigger an alert message when both the phone number and email entered are valid. Any assistance from you all would be greatly appreciated! $sc ...

How can I make Bootstrap Carousel slides transition as I scroll?

I have implemented the Bootstrap carousel on my website, but I am looking to customize its functionality. Specifically, I would like the slides to change whenever the user scrolls with their mouse. Is there a way to achieve this using Bootstrap Carousel? ...

Passing information from a Node.js backend to a frontend JavaScript

I am currently facing challenges in passing variables from my NodeJS backend to a JS script. The backend code snippet resembles the following: app.js const express = require('express'); const app = express(); const path = require('path&apos ...

how to show an error in a modal window when encountering an error

Using Blazor and Blazorstrap, typically when the server disconnects, an "Error" message is displayed. However, with the BsModal from Blazorstrap, it appears in the background layer, making it unresponsive. How can this be fixed? Is it possible to close the ...

Cut the text within each individual container

For many of you, the question I'm about to ask is quite simple. Take a look at the following HTML code: <div class="content" id="content"> <div class="container" id="container"> <h1>Title</h1> <img class ...

Establishing the folder organization for Express Handlebars

I work with NodeJs, Express, and Handlebars. The main file for my server is named app.js const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); app.engine('handlebars', ex ...

Utilizing dual submit inputs in a single form with Ajax functionality in Django

This question has been asked three times now, but unfortunately there seems to be no expert available to provide an answer. When using the method in view.py without JavaScript code, everything functions perfectly for both saving and calculating in one for ...