How to create a dynamic object in a loop? - javascript

Basically I want to create one large object of many object in JavaScript. Something like:
var objects = {}
for (x)
objects.x = {name: etc}
Any ideas?

var objects = {};
for (var x = 0; x < 100; x++) {
objects[x] = {name: etc};
}

An actual implementation
Populate a container object with 100 other objects.
<script>
var container = { }; // main object
// add 100 sub-object values
for(i = 0; i < 100; ++i) {
container['prop'+i ] /*property name or key of choice*/
= { 'a':'something',
'b':'somethingelse',
'c': 2 * i
};
}
TEST THE Results - iterate and display objects...
for(var p in container) {
var innerObj = container[p];
document.write('<div>container.' + p + ':' + innerObj + '</div>');
// write out properties of inner object
document.write('<div> .a: ' + innerObj['a'] + '</div>');
document.write('<div> .b: ' + innerObj['b'] + '</div>');
document.write('<div> .c: ' + innerObj['c'] + '</div>');
}
</script>
Output is like
container.prop0:[object Object]
.a: something
.b: somethingelse
.c: 0
container.prop1:[object Object]
.a: something
.b: somethingelse
.c: 2
container.prop2:[object Object]
.a: something
.b: somethingelse
.c: 4
etc...

Using object[propertyname] is the same as using object.propertyname and hence we can dynamically create object keys with object[propertyname] format
for eg:
var fruits = ["Apple", "Orange", "Banana","Grapes"];
var colors = ["red", "Orange", "yellow","blue"];
var newObj = {};
for (var i = 0; i < fruits.length; i++) {
newObj[fruits[i]] = colors[i];
}
console.log(newObj);

Try this
var objects = new Array();
var howmany = 10;
for (var i = 0; i < howmany; i++)
{
objects[i] = new Object();
}

//On Nested Obj like that
var playersCount = {
"Players" : {}
}
var exempleCount = 5;
for(i=0; i <= exempleCount;i++){
var BadID = Math.floor(Math.random() * 10000);
playersCount.Players["Player_"+i] = {
"id":BadID,
"xPos":0,
"yPos":0,
"zPos":0
};
}
console.log(playersCount);

Related

Calling all possible arrays from the length of another array

What I'm working on is a menu that auto updates its entries based on an array length. It adds groups of 10 objects' properties (in this case "IDnumbers") to the menu if a new object is added to the array.
var arraysOfObject = [], obj = {"IDNumber": ""};
for(i = 0; i<42; i++){
arraysOfObject.push({"IDNumber": "Number " + i});}
Above is the array holding 42 objects with a specific property.
var array2 = [];
var leftOver = arraysOfObject.length % 10;
var groupsOfTen = (arraysOfObject.length - leftOver)/10;
for (var i = 0; i < groupsOfTen; i++) {
array2.push([]);
for (var j = i*10; j < i*10 + 10; j++)
array2[i].push(arraysOfObject[j]["IDNumber"]);
}
//now the leftover
if (leftOver > 0) {
array2.push([]);
for (var i = groupsOfTen*10; i < arraysOfObject.length; i++)
array2[array2.length-1].push(arraysOfObject[i]["IDNumber"]);
}
The array2 above is the array that stores all the possible arrays that can be grouped by 10 from arraysOfObject. In this case there are 5 inside of it, because 4 arrays holds 40 objects, and 1 array holds the 2 remainders.
That all works fine, but placing the array2 inside the menu displays all possible IDnumbers grouped together, but not grouped individually. I have to declare each possible array inside of it like so sets = [array2[0], array2[1], array2[2], array2[3], array2[4]]; If there's a 6th possible array because object #51 has been added to arraysOfObject, I have to input it with array2[5].
I don't want it to depend on my input, but that it knows the number of possible arrays and that it displays it automatically in sets. How do I do that?
var gui = new dat.GUI();
var guiData = function() {
this.message = "Dat.Gui menu";
this.system = 0;
this.Sets = 0;
};
var data = new guiData();
sets = [array2[0], array2[1], array2[2], array2[3], array2[4], array2[5]];
gui.add(data, 'message', 'Dat.Gui Menu!');
gui.add(data, 'system', {
"1": 0,
"2": 1,
"3": 2,
"4": 3,
"5": 4,
"6": 5,
}).name('system #').onChange(function(value) {
updateSets(value);
});
gui.add(data, 'Sets', sets[0]).onChange();
function updateSets(id) {
var controller = gui.__controllers[2];
controller.remove();
gui.add(data, 'Sets', sets[id]).onChange();
data.Sets = 0;
gui.__controllers[2].updateDisplay();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.6.1/dat.gui.min.js"></script>
<script>
var arraysOfObject = [], obj = {"IDNumber": ""};
for(i = 0; i<42; i++){
arraysOfObject.push({"IDNumber": "Number " + i});}
var array2 = [];
var leftOver = arraysOfObject.length % 10;
var groupsOfTen = (arraysOfObject.length - leftOver)/10;
for (var i = 0; i < groupsOfTen; i++) {
array2.push([]);
for (var j = i*10; j < i*10 + 10; j++)
array2[i].push(arraysOfObject[j]["IDNumber"]);
}
//now take care of the leftover
if (leftOver > 0) {
array2.push([]);
for (var i = groupsOfTen*10; i < arraysOfObject.length; i++)
array2[array2.length-1].push(arraysOfObject[i]["IDNumber"]);
}
</script>
Not the issue at hand, but I was playing around with the dat.gui as you posted it and was wondering if the dropdown could be refilled without removing/adding/etc. It seems to work with .options. (NB The initialization code makes heavy use of ES6, but can work without. The system menu is created dynamically from the sets array)
let arraysOfObject =Array.from({length:42}, (o,i) => "Number " + i),
ch =10, sets = Array.from({length:Math.ceil(arraysOfObject.length/ch)}, (a,i) => arraysOfObject.slice(i*=ch, i+ch));
var gui = new dat.GUI();
var guiData = function() {
this.message = "Dat.Gui menu";
this.system = 0;
this.Sets = 0;
};
var data = new guiData();
gui.add(data, 'message', 'Dat.Gui Menu!');
gui.add(data, 'system', sets.reduce((obj,s,i) => (obj[i+1] = i, obj), {})).name('system #').onChange(updateSets);
let controller = gui.add(data, 'Sets');
updateSets(0);
function updateSets(id) {
controller = controller.options(sets[data.Sets = id]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.6.1/dat.gui.min.js"></script>
I think the easiest solution would be to use ES2015's spread operator which I don't know if you would want to use yet...
ES2015 method (demo)
sets = [...array2];
There are a few other changes in the demo to set the system variable
But after taking a closer look, you can optimize the code by using the method from this SO answer to chunk your array using slice(). Also, I'm not sure why an object was used to create array entries when it just ends up as a string... demo
var arraysOfObject = [],
system = {},
chunk = 10,
size = 92;
for (var i = 0; i < size; i++) {
arraysOfObject.push("Number " + i);
}
var sets = [];
var index = 0;
for (i = 0; i < size; i += chunk) {
sets.push(arraysOfObject.slice(i, i + chunk));
system[index + 1] = index++;
}
var gui = new dat.GUI();
var guiData = function() {
this.message = "Dat.Gui menu";
this.system = 0;
this.Sets = 0;
};
var data = new guiData();
gui.add(data, 'message', 'Dat.Gui Menu!');
gui
.add(data, 'system', system)
.name('system #')
.onChange(function(value) {
updateSets(value);
});
gui.add(data, 'Sets', sets[0]).onChange();
function updateSets(id) {
var controller = gui.__controllers[2];
controller.remove();
gui.add(data, 'Sets', sets[id]).onChange();
data.Sets = 0;
gui.__controllers[2].updateDisplay();
}

How do you add/delete methods in an object using a for-loop?

I have an array of 'users' that gets data added/deleted to it. I also have an object 'temp' that will generate a methods based on how many indexes are in the array.
Here's the code I have so far:
var users = [1, 2];
var index = users.length;
var temp = {};
function newTemp(object){
var index = users[object]; //assigns an index #
if(index === undefined){
index = users.length;
users[object] = index;
}
users[index] = object;
for (var i = 0; i < users.length - 1; i++){
temp.['check' + i] = function(){console.log('checking ' + i);}
}
}
newTemp(index);
Ideally, based on how much data is in 'users' I would like 'temp' to contain something like this:
var temp = {
check0 : function(){
console.log('checking ' + 0);
},
check1 : function(){
console.log('checking ' + 1);
}
}

JavaScript arrays declaration ways difference

This could be a pretty basic question, in JavaScript, what's difference between:
var userDetails = {};
var usersList = [];
I was reading an article which had following code:
function GetSampleUsersList() {
var userDetails = {};
var usersList = [];
for (var i = 1; i <= 3; i++) {
userDetails["UserId"] = i;
userDetails["UserName"] = "User- " + i;
userDetails["Company"] = "Company- " + i;
usersList.push(userDetails);
}
return JSON.stringify(usersList);
}
Thanks
This is a pretty basic question.
var o = {}
initializes an empty object. Then you assign its properties.
var a = []
initializes an empty array. You then add the newly created object to the array
a.push( o );
You are using for every iteration the same userDetails, because you overwrite just the properties and while you have pushed the same object, you have always the same content for every element in the array.
function GetSampleUsersList() {
var userDetails = {};
var usersList = [];
for (var i = 1; i <= 3; i++) {
userDetails["UserId"] = i;
userDetails["UserName"] = "User- " + i;
userDetails["Company"] = "Company- " + i;
usersList.push(userDetails);
}
return JSON.stringify(usersList);
}
console.log(GetSampleUsersList());
Better use a new empty object for every loop.
function GetSampleUsersList() {
var userDetails;
var usersList = [];
for (var i = 1; i <= 3; i++) {
userDetails = {}; // this is necessary
userDetails["UserId"] = i;
userDetails["UserName"] = "User- " + i;
userDetails["Company"] = "Company- " + i;
usersList.push(userDetails);
}
return JSON.stringify(usersList);
}
console.log(GetSampleUsersList());
function GetSampleUsersList() {
var userDetails = {}; //created an empty object userDetails
var usersList = []; //created an empty array userDetails
for (var i = 1; i <= 3; i++) { //looping to add property and value in object and for each iteration object is getting pushed into array at an index i.
userDetails["UserId"] = i;
userDetails["UserName"] = "User- " + i;
userDetails["Company"] = "Company- " + i;
usersList.push(userDetails); // pushing object {"UserId":i, "UserName":"User-i", "Company":"Company-i"} into array
}
return JSON.stringify(usersList); // Parsing the object into javascript string
}
var userDetails = {}; -- object notation in javascript
var usersList = []; is an array notation in javascript.
for more infomation refer here http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/

Alternately Join 2 strings - Javascript

I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source

make variable from variable javascript

i am trying to add data to an array where part of the array name is a variable.
if that makes sense?
this is my coding, i think its something to do with the ["charts"[d]] part but nothing is being added to the arrays
var
charts0 = [],
charts1 = [],
charts2 = [],
charts3 = []
var newdata = data.split("|");
var newdates = dates.split(",");
for (i = 0; i < newdates.length; i++) {
for (d = 0; d < newdata.length; d++) {
var dataparts = newdata[d].split(",");
["charts"[d]].push({x: newdates[i], y: dataparts[i+1]});
}
}
Use an object literal as an associative array.
var charts = {
charts0: [],
charts1: []
};
/* ... */
charts['charts' + d].push( // ...
But if you are going to do this, you could simply use an array, where the indices are implicit:
var charts = [[],[]];
/* ... */
charts[d].push( // ...
Create a new object with your arrays like
var ch = {
charts0: [],
charts1: [],
charts2: [],
charts3: []
}
Then you'll be able to do ch["charts" + d][i] etc..
The way you are doing it right now is not possible (without using eval, which you shouldn't). You can however add an extra 'layer' with your variables by using an object. Like so:
var myData = {
charts0: [],
charts1: []
charts2: []
charts3: []
};
var newdata = data.split("|");
var newdates = dates.split(",");
for (i = 0; i < newdates.length; i++) {
for (d = 0; d < newdata.length; d++) {
var dataparts = newdata[d].split(",");
myData['charts' + d].push({x: newdates[i], y: dataparts[i+1]});
}
}

Categories