Add values to an array - javascript

How to add values to an empty array? I have tried the following but it is not working:
var student = [{}];
for (var i = 0; i < 5; i++) {
student[i].name = i;
student[i].id = "1";
student.push(student[i]);
}
var a = JSON.stringify(student);
alert(a);
It give output 6 time repeated last values not 5 time :
'[{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"}]'

var student = [{}];
This creates a javascript array containing one empty object
student[i].name = i;
student[i].id = "1";
For i = 0, this alters that empty object.
student.push(student[i]);
You then push that altered object to the array it already exists in. You now have two identical values in the array.
Two items after first push. This is repeated five times.
Pushing an item adds it to the array. There's usually no point in pushing an element that's already in the array. Create a new object and push that. The array doesn't have to be pre-populated with an empty object to modify.
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
name: i,
id: '1'
});
}

In your original code, you are setting the object at student[i]'s values, then just pushing it again onto the array, then setting those values all over again.
You need to push a new object each time:
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
id: i,
name: i
});
}
var a = JSON.stringify(student);
alert(a);

You are using the same name for the list and the new object. When you change the name of the list to students, your problem is fixed. Solution below:
var students = [{}];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);

try ;
var students = [];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);

Your array is not empty. It already contains an object. Maybe the problem is easier to see if we put the object in an extra variable and omit the the loop:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj.name = 2;
student.push(obj)
The question is: How many objects are we creating here? The answer is one, namely var obj = {};. We then add some properties to the object (name) and add it to the array (student.push(obj)).
What comes next is crucial: We change the existing properties of the object and assign different values to it. Then we add the object to the array again. Even though student contains two elements, but they refer to the same value (which can be easily verified with student[0] === student[1]).
If you want to create an array of different objects, you have to create those objects. In our example this would be:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj = {}; // <- create a new object
obj.name = 2;
student.push(obj)
For your code that means that you have to create a new object in each iteration of the loop, not just one outside of it.
Reading material about arrays and objects:
Eloquent JavaScript - Data structures: Objects and Arrays
MDN - Working with objects
MDN - Array object

Since you are pushing object, its reference change every time to current value so at last it shows the output as last value.
Try this
var student = [{}];
for (var i = 0; i < 5; i++) {
var obj = new Object();
obj.name = i;
obj.id = "1";
student.push(students);
}
var a = JSON.stringify(student);
alert(a);

Related

JavaScript interpolation and template literals not allowing me to push to array

I have a need for referencing an array name out of other variables values. Below is a simple program that doesn't push the value into an array. I was hoping someone could determine why. There is no runtime error but when you print the array it has not been pushed. I am creating a 4 person card game that currrently works by having a 2D array with 4 players. I want to deal the cards to P0cards P1Cards.... instead of the 2D players[[],[],[],[]] array.
My idea of using $p{i}.push(card) is not working
class Card{
constructor(suit, value){
this.value = value;
this.suit = suit;
}
}
let deck = [];
let players = [[],[],[],[]];
var p0Cards = [];
var p1Cards = [];
var p2Cards = [];
var p3Cards = [];
function deal(){
//players 1,2,3,4
for(let i = 0; i < 4; i++){
//cards 1,2,3,4,5,6
for(let j = 0; j < 6; j++){
let card = deck.pop();
//players[i].push(card);
`$p{i}.push(card)`; //this is what I would like to do.
}
}
}
Can you make your arr part of an object? Then you can access it with the use of a string.
let myVars = {}
myVars.arr = []
let x = 'arr';
myVars[x].push(2);
myVars.arr.push(3);
console.log(myVars.arr);
// myVars.arr = [2, 3]

Two dimensional arrays populating does not work javascript

When i try to create two dimensional array in javascript using loop, it gives me following error:
Cannot set property 'indexis' of undefined
Code:
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i]; //assuming headingsArray exist
indexes[i]['valueis'] = rows[0][i]; //assuming rows exist
}
}
You need to create the inner arrays/objects as well, or else index[i] is undefined, so index[i]['indexis'] will throw an exception.
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
indexes[i] = {}; //<---- need this
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i];
indexes[i]['valueis'] = rows[0][i];
}
}
You described it as a multidimensional array, but you're using it as though it's an array of objects (because you're accessing named properties, instead of numbered properties). So my example code is creating objects on each iteration. If you meant to have an array of arrays, then do indexes[i] = [], and interact with things like indexes[i][0] rather than indexes[i]['indexis']
You need an object before accessing a property of it.
indexes[i] = indexes[i] || {}
indexes[i]['indexis'] = i;
define temp var with field initialise to null & use push() function of JavaScript
for (var i = 0; i < headingsArray.length; i++) {
var temp={indexis: null,headingis:null,valueis:null};;
if (headingsArray) {
temp['indexis'] = i;
temp['headingis'] = headingsArray[i]; //assuming headingsArray exist
temp['valueis'] = rows[0][i];
indexes.push(temp);
}
}

pushing objects in a array inside a loop

I am trying to push objects into an array inside a for loop. The expected data structure is
[{"valueItem":"item0"}, {"valueItem":"item1"}, {"valueItem":"item2"}, {"valueItem":"item3"}, {"valueItem":"item4"}]
The code I have is
var arr = [];
var obj = {};
for(var i = 0; i < 5; i++){
arr.push(obj.valueItem = 'item'+i);
}
console.log(arr)
But the what I get back is
["item0", "item1", "item2", "item3", "item4"]
What am I doing wrong?
try:arr.push({"valueItem":"item"+i});
Ok, to clarify, you have to push an object in your array to get your expected array.
push(obj.valueItem = 'item'+i) works sortof because you are assigning inside push.
The below works ;)
var arr = [];
for(var i = 0; i < 5; i++){
var obj = {};
obj.valueItem = 'item' + i;
arr.push(obj);
}
console.log(arr)
By doing this arr.push(obj.valueItem = 'item'+i);
you are not pushing obj into the array, you are making an assignment
obj.valueItem = 'item'+i
the result of an assignment is the returned value, in this case it is item+i,
to push objects into an array do this
arr.push({
valueItem: "item0"
})
First define object, then push it to array:
var arr = [];
for(var i = 0; i < 5; i++){
arr.push({valueItem: 'item'+i});
}
console.log(arr)
Based on your try:
var arr = [];
for(var i = 0; i < 5; i++){
var obj = {};
obj.valueItem = 'item'+i
arr.push(obj);
}
console.log(arr)
Looks like you're not actually creating a new object for each loop. Maybe try:
arr.push( { valueItem: 'item'+i } );.
The {} will create a new hash object, which we would push onto the array.
In your inital code you only made one object, so the thing you were pushing was the return value of obj.valueItem='item'+i. Since the return value of a string assignment would be the actual string, you were just creating an array of strings.
Your expected result has a different object for each element. Even though they are are similar in that they have a valueItem proprerty, they are all different. So you need to create a new one on each loop iteration. You need
arr.push({valueItem:"item"+i});
which creates a new one each time.

Array push still using previous reference?

I have following code:
var students = [];
for(var i = 0; i < classes.length; i++) {
var student = {};
student = classes[i].student;
student.teacher = classes[i].teacher;
students.push(student);
}
Somehow the students will print same object for all its contents, although I have put var student = {}; inside the loop, thus it must not refer to same reference.
Anyone has idea why this happens?
You put student = {} inside the loop, then on the line immediately following that one you overwrote that by assigning student = classes[i].student.
If the intention is to make a copy of whatever classes[i].student is you can use the Object.assign() method:
var student = Object.assign({}, classes[i].student);
In context:
var students = [];
for(var i = 0; i < classes.length; i++) {
var student = Object.assign({}, classes[i].student);
student.teacher = classes[i].teacher;
students.push(student);
}
(Note that Object.assign() doesn't do a deep copy - I'm not sure if that matters because you haven't shown what the classes array structure is.)
You could also use the .map() method instead of an explicit for loop:
var students = classes.map(function(c) {
var student = Object.assign({}, c.student);
student.teacher = c.teacher;
return student;
});

How to create a multidimensional array in JavaScript?

How can I create a multidimensional array in JavaScript?
I have:
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar = [];
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
If I do:
groupsData.name_of_bar[0]
I get errors:
TypeError: Cannot read property '0' of undefined
TypeError: Cannot set property 'a' of undefined
What am I doing wrong?
JavaScript doesn't support multidimensional arrays per se. The closest you can come is to create an array where the values in it are also arrays.
// Set this **outside** the loop so you don't overwrite it each time you go around the loop
groupsData.name_of_bar = [];
for (var i = 0; i < m; i++){
// Create a new "array" each time you go around the loop
// Use objects, not arrays, when you have named properties (instead of ordered numeric ones)
groupsData.name_of_bar[i] = {};
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
Each iteration through the loop, you are doing groupsData.name_of_bar = [];. This removes whatever else is already in there and replaces it with a blank array.
Also, when you do groupsData.name_of_bar[i]['a'], you need to create groupsData.name_of_bar[i] first.
A way to do this is:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy: data[i].xy,
});
}
Note that in JavaScript, arrays can only be numerically indexed. If you want string indexes, you need to use an object.
Also, if there are no other values in data[i], then you can simplify this even further by doing:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push(data[i]);
}
Heck, why not just use groupsData.name_of_bar = data; and lose the loop altogether?
The way you are declaring your objects are a little off. It looks like you are attempting to create an array of objects.
var groupsData = {name_of_bar: []},
m = 4,
i = 0;
for(; i < m; i++) {
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy = data[i].xy
});
}

Categories