pushing objects in a array inside a loop - javascript

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.

Related

adding an array into an array at a particular position (based on key value) in javascript

I searched a lot, but I could not get a satisfactory answer on the net. In javascript, how do I add an array into another multidimensional array at a particular position based on a key value?
finalArray = []; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = [];
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp; // This gives an error
}
basically, I have
group = [ 'alpha' ,'beta', 'gamma' ]; //this array generated dynamically
my finalArray should be like,
finalArray['alpha'] = [ some records ];
finalArray['beta'] = [ some records ];
....
As far as I know, the way to add array into another array is to use .push() method, but that creates indices as 0, 1, 2... which is not desired. Please help me out
You have to use Object instead of Array. Make the following changes in the code
finalArray = {}; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = {};
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp;
}
console.log(finalArray); //to see the object key value structure
now you can reference the values in finalArray with group[i] name. Hope this helps
You have to define your finalArray variable as Object instead of and Array:
var finalArray = {}; //or better in your case finalMap
var group = [ 'alpha' ,'beta', 'gamma' ];
var finalArray = {}; //declare it object as you dont want 0,1 indexes
for (var index in group){
finalArray[group[index]] = "some records/arry of records"
}
console.log(finalArray);
DEMO

Add values to an array

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);

Initialization and Assigning of 2D array in javascript

var array = [];
var arr = [];
var i;
for (i = 0; i < 2; i++) {
var temp = [];// using array[i] = new Array() works fine
array.push(temp);
arr.push(temp);
}
array[0].push(1);
arr[0].push(2);
alert(array[0]);
The above javascript code gives [1,2] as out put.
Where as using 'new Array()' instead of 'push([])' gives [1].
I was able to find the issue, but I don't get reason why. can some one explain this
arrays work like pointers to some location in the memory so the arr variable dosent store the actual values that u are pushing
in fact it is pointing to a memory location where the values are stored
and in this case it points to "temp"
so when you write
for (i = 0; i < 2; i++) {
var temp = [];// using array[i] = new Array() works fine
array.push(temp);
arr.push(temp);
}
what is happening is that in each loop its creating a new temp but both of "array an arr"
are pointing to the same location in the memory so when one of them is modefing the contents of this location its changing the data that the other one is pointing to
meanwhile if use the following code
var array = [];
var arr = [];
var i;
for (i = 0; i < 2; i++) {
array[i] = new Array();
arr[i] = new Array();
}
array[0].push(1);
arr[0].push(2);
alert(array[0])
what will hapen here is that each time the "new Array()" is called it will allocate a new variable in the memory and pass-back its location to the array pointer that you created "array & arr"
so now each one of the previos pointers is pointing to a different place in the memory
This code will create one array and put reference to it inside both arrray and arr
var temp = [];// using array[i] = new Array() works fine
array.push(temp);
arr.push(temp);
So when you run:
array[0].push(1);
arr[0].push(2);
alert(array[0]);
Then, you first push 1 to original tmp, that has reference in array[0], and then push 2 again to tmp, which is too in arr[0], so you'll get [1,2] as a result.
I didn't see your full alternative code but i assume if you have this in your for loop:
array[i] = new Array();
arr[i] = new Array();
Then, you'll have two separate arrays in array and arr, so when you run again:
array[0].push(1);
arr[0].push(2);
alert(array[0]);
alert(arr[0]);
You'll get 1 in array[0] and 2 in array[1].

JSON Assoc Array to Variables?

I have a JSON associate array
[{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]
and I want to make it so that it becomes an array where
{
theatre = Test
time = 5:00pm
},
{
theatre = Testing2
time = 4:30 pm
}
But I can't figure out how to take a key name and make it a value...
Any help? I was looking at Object.keys but I couldn't find a suitable solution.
You have an array with object values. You'd need to loop over them:
var oldArray = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}];
var newArray = [];
for (var i = 0; i < oldArray.length; i++) {
var keys = Object.keys(oldArray[i]);
newArray.push({
theatre: keys[0],
time: oldArray[i][keys[0]]
});
}
http://jsfiddle.net/FNAtw/
This will give you an array stored in newArray with two elements. The first element is an object with kvps theatre: 'Test' and time: '5:00pm'. The second element is an object with kvps theatre: 'Testing2' and time: '4:30pm'.
Try this workaround:
var json = '[{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]';
var betterJson = json.replace('{"', '{"theatre":"').replace('":"','",time:"');
If the JSON is always as simple as above, then this should work. But it's brittle...
If you have a JS object, you could use Object.keys. That will work in the latest browsers.
You can also loop each item and just save the 1st item.
var result = [];
var str = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}];
for (var i = 0; i < str.length; i++) {
var obj = {};
foreach (var key in str[i]) {
obj.theatre = key;
obj.time = str[i][key];
}
result.push(obj);
}
May be a bit clunky, BUT should work cross-browser.
var js = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]
var newJSON = []
for(var i = 0; i< js.length; i++) {
for( var key in js[i]) {
if(js[i].hasOwnProperty(key)) {
var tmpJS= {};
tmpJS['theater'] = key;
tmpJS['time'] = js[i][key];
newJSON.push(tmpJS);
}
}
}

Creating array of objects dynamically based on length

I have the length of my previous object and i need to create a new array of objects based on the length with new key's.
Length = 3;
var newArray = [];
for(var i =0; i <3; i++){
var Object = {};
Object['newKey'] = 1;
newArray.push(Object);
}
This would eventually create newArray of Objects whose length is 3 containing something like this.. newArray[0],[1],[2].
Am i doing this correctly, please do suggest me if anything wrong or a better way to do this.
Here's what you wrote (I think), just shortened a bit (and fixed the capitalization of variable names)
var length = 3;
var newArray = [];
for( var i = 0 ; i < length ; i++ ) {
newArray.push({newKey: 1});
}
but to be honest it's unclear to me exactly what you're trying to accomplish
You could make it slightly more dynamic by referencing the variable for length.
Example updated per comments:
var length = 3,
newArray = [];
for ( var i=0; i<length; i++ ) {
var tempObj = {};
tempObj['newKey'] = 'SomeValue';
newArray.push(tempObj);
}
I didn't really do more than clean up what you have.

Categories