How to create data model dynamically - javascript

I have this Json data I get from server in javascript
var mydata = JSON.parse('["X","Y","Z"]');
Below I have the following data model in javascript..
var mySchemasList = {
schemas: [new SelectSchemaModel("A", false),
new SelectSchemaModel("B", false),
new SelectSchemaModel("C", false)
]
};
I want to create this model dynamically by getting data ('A','B','C') from mydata..
Any help is sincerely appreciated..
Thanks

Can't you just do something like the following?
var i
var mySchemaList = {schemas:[]};
for (i = 0; i < mydata.length; i++) {
mySchemaList.schemas.push( new SelectSchemaModel(mydata[i], false) );
}

In javascript, objects and arrays are accessed using the . or [] operators. The following two lines does exactly the same thing:
mySchemasList.schemas;
mySchemasList['schemas'];
Also, each member of an object or array act like a variable on its own. So you can assign values, objects or arrays to them:
mySchemasList = {};
When a variable (or property) is declared but not assigned anything its value is undefined. So you can check simply by:
if (mySchemasList === undefined) mySchemasList = {};
Alternatively you can use || short circuiting since undefined is considered false:
mySchemasList = mySchemasList || {};
putting this all together, the following two examples does exactly the same thing.
Example 1:
var mySchemasList = {
schemas : []
}
Example 2:
var mySchemasList = {};
mySchemasList.schemas = [];
Now that you've created an array at mySchemasList.schemas you can start pushing other objects into it:
mySchemasList.schemas.push(new SelectSchemaModel("A", false));
mySchemasList.schemas.push(new SelectSchemaModel("B", false));
mySchemasList.schemas.push(new SelectSchemaModel("C", false));
Wrapping it up in a for loop parsing the JSON data, you'd do this:
var mydata = JSON.parse(ajax.responseText);
for (var i=0; i<mydata.length; i++) {
mySchemasList.schemas.push(new SelectSchemaModel(mydata[i],false));
}

Related

JavaScript Data Not Appending to Array

I have an object of values and I am trying to populate two arrays with the keys and values from the object.
My Object:
obj = {19455746: 7476, 22489710: 473}
Loop attempting to append data:
var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
sensorNameArray.push[i];
sensorDataArray.push[obj[i]];
}
At the moment the two arrays are printing out as empty. My expected outout would be something like:
sensorNameArray = [19455746, 22489710];
sensorDataArray = [7476, 473];
push is a function, not an array, it uses parenthesis not brackets :
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
The syntax push[] doesn't invoke the function, it tries to access a property of the function object. It doesn't throw an error because in Javascript, functions ARE objects and this syntax is technically valid.
So, just fix the syntax to push() in order to actually invoke the function.
You are using square braces []
but array.push() is a function so use circle braces instead
Try the following code
obj = {19455746: 7476, 22489710: 473};
var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
This is working and tested.
A different syntax (more elegant IMO) :
var sensorNameArray = Object.keys(obj)
var sensorDataArray = Object.values(obj)
or :
var sensorDataArray = sensorNameArray.map( key => obj[key] )
Best way to deal with JSON is use lodash or underscore.
_.key() and _.value are functions for your requirement.
Eg.:
obj = {19455746: 7476, 22489710: 473};
sensorNameArray = _.keys(obj);
sensorDataArray = _.values(obj);
If you want to proceed in your way, then you can use parenthesis as push inbuilt function of Javascript for inserting element into array.
Correct is:
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}

Strange behaviour of array in double for loops - JavaScript

I have rootObject which holds childObject as a value. I use two for loops to get values from childObject and put them to array. Array is cleared in every iteration of outer loop.
var childObject = new Object();
for (var i = 0; i < 3; ++i) {
childObject[i] = i*i;
}
var rootObject = new Object();
rootObject[0] = childObject;
I am using console.log(resultArray) to observe array. And this is what I got:
When clearing before second for loop
var resultArray = []
for ( var rootKey in rootObject){
resultArray.length = 0; //clearing array
for ( var childKey in rootObject[rootKey]){
resultArray.push([ parseInt(childKey), rootObject[rootKey][childKey] ]);
}
console.log(resultArray);
}
I get [Array[2], Array[2], Array[2]
When clearing after second for loop
var resultArray = []
for ( var rootKey in rootObject){
for ( var childKey in rootObject[rootKey]){
resultArray.push([ parseInt(childKey), rootObject[rootKey][childKey] ]);
}
console.log(resultArray);
resultArray.length = 0; //clearing array
}
I get []
Why result is different?
EDIT
I am using Firefox 29
http://jsfiddle.net/xf78k/5/ <-- good
http://jsfiddle.net/xf78k/6/ <-- bad
You store a reference to the array into your var, and print it through the console, that will show you the realtime (dynamic) state of the array.
In other words, the console will show you three times the same objects, in both cases, and its state will be the final state of resultArray.
If you converted it to string, or printed its length, you'd have the expected result, because it would be a primitive value, and the console wouldn't keep track of its reference.
Taste the difference:
var childObject = new Object();
for (var i = 0; i < 3; ++i) {
childObject[i] = i*i;
}
var rootObject = new Object();
rootObject[0] = childObject;
var resultArray = []
for ( var rootKey in rootObject){
for ( var childKey in rootObject[rootKey]){
resultArray.push([ parseInt(childKey), rootObject[rootKey][childKey] ]);
}
console.log(resultArray.length);
resultArray.length = 0; //clearing array
}
One suggestion: don't initialize plain objects with "new Object()".
var childObject = {};
is to be preferred instead.
EDIT: why you'd rather prefer the literal syntax to init objects
Try this code:
var a = new Object(1);
var b = new Object("1");
The result is that a is a Number(), and b is a String, because Object accept an optional parameter that drives which constructor is used for the object.
So, it is error prone.
Now try this:
Object = function () {
//xmlhttp=new XMLHttpRequest("malicious site"); ...
console.log("XSS attack")
}
var c = new Object();
any script can override it, while {} is safer.
Finally, due to JS engines optimization, the literal syntax leads to better performance.
More
console.log does lazy and async evaluation of variables. Since arrays are passed by reference, it's not strange for it to reflex the value it has after clearance.
If you insert a breakpoint before clearing you should see the array with its elements.

Push to a javascript array if it exists, if not then create it first

Is there a way for this line to always work and not throw TypeError: Cannot read property 'Whatever' of undefined
var MyArray = [];
MyArray[StringVariableName][StringVariableName2].push("whatever");
Try this:
var MyArray = [];
MyArray[StringVariableName] = MyArray[StringVariableName] || [];
MyArray[StringVariableName][StringVariableName2] = MyArray[StringVariableName][StringVariableName2] || [];
MyArray[StringVariableName][StringVariableName2].push("whatever");
You could even, through the power of expressions, do this with a one-liner.
(MyArray[StringVariableName][StringVariableName2] || (MyArray[StringVariableName][StringVariableName2] = [])).push("whatever");
You could use the literal syntax to set things up like you'd have them:
var myObj = {
StringVariableName: {
StringVariableName2: []
}
};
myObj.StringVariableName.StringVariableName2.push("whatever");
I think instead of using array in the first place, use object if your keys are not integers.
In Javascript Arrays are also object So it is not wrong to do this
var a = [];
a['key'] = 'something';
console.log(a); //Gives []
I think it is conceptually wrong So instead of using Array to hold such pair of data you should use objects. See this:
var myObject = myObject || {};
myObject[str1] = myObject[str1] || {};
myObject[str1][str2] = myObject[str][str2] || [];
// Now myObject[str1][str2] is an array. Do your original operation
myObject[str1][str2].push("whatever");
To check without getting an error:
this snippet allows you to check if a chained object exists.
var x;
try{x=MyArray[name1][name2][name3][name4]}catch(e){}
!x||(x.push('whatever'));
from
https://stackoverflow.com/a/21353032/2450730
Shorthand creation of object chains in Javascript
this function allows you to create chained objects with a simple string.
function def(a,b,c,d){
c=b.split('.');
d=c.shift();//add *1 for arrays
a[d]||(a[d]={});//[] for arrays
!(c.length>0)||def(a[d],c.join('.'));
}
usage
var MyArray={};//[]
def(MyArray,'name1.name2.name3.name4');//name1+'.'+name2....
from
https://stackoverflow.com/a/21384869/2450730
both work also for arrays with a simple change.replace {} with []
if you have any questions just ask.

Javascript multidimentional array undefined object error

I am trying to make a two dimensional array out of two one dimentional arrays with this code:
var PassAssoArr = new Array();
for(k in PassPourcentNames) {
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
However, I get the error message: " 'undefined' is null or not an object " and it points to the first line after the for statement.
PassPourcentNames and PassPourcentValue have the same number of elements and none of the values are null. The first one contain strings and the second one integers.
Any help is greatly apreciated.
var PassAssoArr = new Array();
for(k in PassPourcentNames) {
PassAssoArr[k] = new Array();
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
Also instead of new Array() you can use []
var PassAssoArr = [];
for(k in PassPourcentNames) {
PassAssoArr[k] = [];
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
I believe this is actually faster in most JS engines.
First define PassAssoArr[k] = []; before assigning to [0] and [1].
Javascript does not support true multi-dimensional arrays.
You're trying to use nested arrays without creating the inner arrays.
You need to put an array into each element of the outer PassAssoArr:
PassAssoArr[index] = []; //Empty array literal
You're only defining one dimension of PassAssoArr - you need to set PassAssoArr[k] = new Array();
Try just doing:
PassAssoArr[k] = new Array(PassPourcentNames[k], PassPourcentValue[k]);

javascript push multidimensional array

I've got something like that:
var valueToPush = new Array();
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
the result is [];
what am i do wrong?
Arrays must have zero based integer indexes in JavaScript. So:
var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);
Or maybe you want to use objects (which are associative arrays):
var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
which is equivalent to:
var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.
Use []:
cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
or
arrayToPush.push([value1, value2, ..., valueN]);
In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.
Instead, declare valueToPush as an object and push that onto cookie_value_add:
// Create valueToPush as an object {} rather than an array []
var valueToPush = {};
// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
// View the structure of cookie_value_add
console.dir(cookie_value_add);

Categories