I need to create a list of struct type (complex model) on JavaScript using ASDP.NET MVC3
var myItems = new Array(#Model.Count());
var CreatedItem;
for (i = 1 ; i<= #Model.Count()-1;i++)
{
CreatedItem = {
'DayPartID': i,
'Name': $("#Name_"+i).val(),
'IsEnable': $("#IsEnable_"+i).val(),
'Time': $('#timepicker-'+ i).val()
};
myItems.push(CreatedItem);
alert(myItems[i]);
}
Problem is that I can not obtain "myItems" filled correctly after repetitive structure "for" ends.
You're initializing your array like:
var arr = new Array(2);
Then you do:
arr.push("foo");
This will give you:
[ undefined, undefined, "foo" ]
Either change the initialaztion to an empty array like:
var myItems = [];
Or don't push, but set, like:
myItems[i] = CreatedItem;
Also, your loop starts at 1 - that's weird. Change to:
for (i = 0 ; i < #Model.Count(); i += 1) {
Related
Is there an efficient way to loop through the keys in a JSON array that start with the key name 'option' and either loop through them all or set a max?
I'm currently doing this following:
$.each(shopifyProductJSON.variants, function(index, variant) {
variantOptions = new Array();
variantOptions.push(variant.option1);
variantOptions.push(variant.option2);
variantOptions.push(variant.option3);
});
Which is fine but want it to be more dynamic in case more options are added in the future.
An example of part of the JSON array for each variant:
inventory_management: null
inventory_policy: "deny"
inventory_quantity: 0
old_inventory_quantity: 0
option1: "Bronze"
option2: "Satin Gold"
option3: "600mm"
position: 1
price: "550.00"
I thought this would've worked...
variantOptions = new Array();
for (i = 1; i < 4; i++) {
var key = 'option' + i;
variantOptions.push(key);
}
To solve your immediate issue you need to access the objects properties in the loop, not push the string in to the array:
let variantOptions = [];
for (i = 1; i < 4; i++) {
var key = 'option' + i;
if (data.hasOwnProperty(key)) {
variantOptions.push(data[key]);
}
}
That being said, if the options are going to be of a dynamic length it makes far more sense to return them as an array instead of individual numbered properties, assuming you have control over the response format.
You could change the response to this:
{
inventory_management: null
inventory_policy: "deny"
inventory_quantity: 0
old_inventory_quantity: 0
options: ['Bronze', 'Satin Gold', '600mm'],
position: 1
price: "550.00"
}
Then the JS to access the options becomes a simple property accessor:
let variantOptions = data.options;
I'm quite new to JavaScript and programming in general and figured I'd hone my abilities by working on a small project. The idea is that I have a form for information on an event, an input for the name, date, time and a small thumbnail image.
I want each event to be an object inside of an array, so I would have something like:
var concerts = {};
for (var i = 1; i < 11; i++) {
window["concert"+i] = new Object();
}
and the array would end up being something:
var concerts = [concert1, concert2, concert3]
and so on.
How could I get this loop to work so that it would take the 3 parameters and create a new object in the array named 'concert'+i? Thanks for reading!
Concerts must be an array:
var concerts = [];
for (var i = 0; i < 10; i++) {
concerts[i] = {
//maybe also giveit a name if you want to:
name:"concert"+i
};
}
You can access it like this:
concerts[0].name="Wacken";//first concert...
Note that this:
window["concert"+i] = new Object();
is very bad style...
First you declare a variable concerts of type object. But you want an array. That first line makes your code very confusing.
You have to start with an empty array:
var concerts = []; // alternatively: new Array();
In the end you'd like to have a structure like this:
[
{ /* object 1 */ },
{ /* object 2 */ }
]
Now you can run a foor-loop and populate the array:
for (var i = 0; i <= 10; i++) {
concerts.push({['concert' + i]: {}});
}
This will return something like:
[
{'concert0': {}},
{'concert1': {}},
// skipped
{'concert10': {}}
]
Later you can populate the objects. This is however not a very nice style. Maybe you should reconsider if it is really necessary to give a name to every object like concert0...10.
Go rather for:
var concerts = [
{
'name': 'concert0',
'location': 'somewhere'
}
// continue with other objects
];
I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
MichaĆ
I have an associative array - indexed by dates. Every element holds another array.
[03/16/2015: Array[3], 03/17/2015: Array[3], 03/18/2015: Array[3], 03/19/2015: Array[3]]
I created it with this code:
array[cellDate][i]=cellText;
How can I get the value for example from cell 03/16/2015 array[2] ??
var text=array['03/16/2015'][2];
With this line of code I got an error.
EDIT:
http://www.traineffective.com/schedule/
I store in that array title of blocks dropped in the schedule (title of block of 'empty' value if cell is empty)
What I want to achive is remeber the order of the blocks for particular weeks , and when user changes week with arrows it loads block based on date withdrowed from array.
Code where I create array :
function saveWeekToArray(array){
var cellDate;
var cellText;
var tmpText;
var i;
workoutsTD.each(function(){
cellDate=$(this).attr("data-day");
array[cellDate]=['','',''];
i=0;
$(this).children('.workout-cell').each(function(){
if (!$(this).hasClass('workout-cell-empty')){
cellText=$(this).find('span').text();
array[cellDate][i]=cellText;
} else {
array[cellDate][i]='empty';
}
i++
});
});
}
Code where I load data from array (One with the error )
function loadBlocksFromArray(array){
var cellDate;
var cellText;
var tmpText;
var i;
workoutsTD.each(function(){
cellDate=$(this).attr("data-day");
i=0;
$(this).children('.workout-cell').each(function(){
if ((array[cellDate][i])!='empty'){
cellText=array[cellDate][i];
$(this).append(createBlock(cellText));
$(this).removeClass('workout-cell-empty');
}
i++;
});
});
}
When you will click sumbit button in console log you will see the structure of array.
I got error while changing the week its :
enter code hereUncaught TypeError: Cannot read property '0' of undefined
In Javascript, there is no concept of an associative array. You either have arrays (which are indexed by numbers) or you have Objects (whose elements are indexed by strings).
What you instead want is an object containing all of your arrays. For example:
var data = {
'3/4/2015' : ['val1', 'val2', 'val3'],
'3/8/2015' : ['val1', 'val2', 'val3']
};
Then you can access your elements in the way that you want:
var ele = data['3/4/2015'][1];
https://jsfiddle.net/x9dnwgwc/
That is the effect what I wanted achive. Thanks for hint Harvtronix!
var jsonObj = { workout : {} }
var i;
var k;
var workoutArray = [];
for(i=1; i<=7; i++){
var newWorkout = i+ "/12/2015";
for (k=0; k<=2; k++){
var newValue = "workoutTitle" + k;
workoutArray[k]=newValue;
}
jsonObj.workout[newWorkout]=workoutArray;
}
console.log(jsonObj);
for(i=1; i<=7; i++){
var newWorkout = i+ "/12/2015";
var tmpArray= jsonObj.workout[newWorkout];
console.log(tmpArray);
}
I have a JSON object that contain a set of key:values. I want to first check if that first the key matches an array value and then if it does to add the value amount to that same buffers array within that array.
Here's my code to hopefully show what I mean:
ws.onmessage = function(evt){
cities = JSON.parse(evt.data);
for(var i=0; i<buffer.length; i++) {
if(buffer[i][0] == cities.clusters) {
buffer[i][1][0]++;
}
console.log(buffer);
}
};
This is my buffer array:
var buffer = [['1',[0]],['2',[0]],['3',[0]],['4',[0]]];
This is the JSON output received from the server:
{"clusters": {"London": 4, "Atlanta": 5}, "time": "2012-11-22 19:56:25"}
So what I want is that the buffer array on this iteration becomes:
var buffer = [['London',[4]],['New York',[0]],['Atlanta',[5]],['LA',[0]]];
At every iteration these amounts then get added to and updated.
I don't know how to do this and I don't think the for loop will be able to do it.
Thanks
I'm going to pretend that your buffer is this:
var buffer = [['London',[0]],['New York',[0]],['Atlanta',[0]],['LA',[0]]];
Then the loop becomes this:
for (var i = 0, item; item = buffer[i]; ++i) {
buffer[i][1][0] = cities.clusters[item[0]] || 0;
}
The expression cities.clusters[item[0]] || 0 uses the value of the respective city or 0 if not defined.
Demo
Assuming all the comments & edits, this should help : (fiddle)
var data = {} ; // From Webservice
var buffer = [['London',[4]],['New York',[0]],['Atlanta',[5]],['LA',[0]]];
var clusters = data.clusters;
for (var i in clusters) for(var j in buffer)
if(buffer[j][i]) buffer[j][i] = cluster[i];