Accessing nested array elements. - javascript

I'm trying to access an element located in a cell inside of an array, that's inside of another array.
I've tried several methods but everything returns undefined.
json:
[
{"assignment":"Tom" , "cell":["Tom", "2013-10-06", "Client 3", "Activity", "Scheduled" ]}
]
jquery:
$.getJSON('data/gridData1.json',function(json){
var grid = json;
filterGrid(grid, ele);
});
This code does return an array perfectly fine.
javascript:
function filterGrid(filter, ele){
var types = ['Activity','Alert','Lead','Notification'];
var newTable = [];
var cs1 = $("option:selected", ele).attr("class");
var option = $("select[name='datagrid_filter'] option:selected").text().trim();
if(cs1 == 'type'){
for(var i = 0; i < types.length; i++){
if(types[i]==option){
for(var k = 0; k < filter.length; k++){
if(**filter[0][0][0].value==option**){
newTable.push(filter[k]);
}
}
break;
}
}
}
buildGrid(newTable);
}
Doesn't return anything, including the first element.
Any ideas would be great, that.

Your array has one element, which is an object, so filter[0] gives you that object.
That object has two properties, assignment and cell, so filter[0].assignment gives you "Tom" and filter[0].cell gives you the inner array.
The inner array has filter[0].cell.length items in it, the first of which is filter[0].cell[0], the second of which is filter[0].cell[1], etc.
To iterate over the items in the inner array do this:
for(var k = 0; k < filter[0].cell.length; k++){
if(filter[0].cell[k]==option){
newTable.push(filter[0].cell[k]);
break;
}
}
...but it's kind of clunky repeating filter[0].cell everywhere, so you can add another variable that is a reference to the inner array:
var cell = filter[0].cell;
for(var k = 0; k < cell.length; k++){
if(cell[k]==option){
newTable.push(cell[k]);
break;
}
}
Your code that tried to use filter[0][0][0].value didn't work because you can't access object properties by numeric index except where the actual property name is a number, and in any case you don't want the .value bit on the end.

Related

Javascript loop push into global array

1.I want to push id[i] into global array.After I pushed then it will be id.length numbers items in each array,but it will be error and says y is not a function.how to solve it?
2.the sendrequest in the bottom will send a xmlhttprequest to server,but I don't understand why it will run first and then the function(parResponse) will be fire after tmpReadRequest.sendReadRequest(); has down.
Thanks a lot
var tes0=new Array();
var tes1=new Array();
var tes2=new Array();
var tes4=new Array();
var tes5=new Array();
function ReadValuePath(id, Variable,id_2) {
var tmpReadCB = function(parResponse)
{
for (var tmpIndex = 0; tmpIndex < parResponse.length; tmpIndex++)
{
var tmpItemValue = parResponse[tmpIndex];//console.log(tmpItemValue);
var tmpValue = (tmpItemValue.mItemValue) ? tmpItemValue.mItemValue : tmpItemValue.mItemResultId;
if(document.getElementById(id[tmpIndex]) != null && document.getElementById(id_2[tmpIndex]).value != 0)
{
document.getElementById(id[tmpIndex]).value = parseFloat(tmpValue).toFixed(2);
}
}
return true;
}
var tmpReadRequest = new OPCReadRequest("DE", tmpReadCB);
for(var z=0;z<5;z++ ){
for(var i = 0; i < id.length; i++)
var y="tes"+z;
y.push(id[i]);
tmpReadRequest.addItem("ab", Variable[i]);
}
}
tmpReadRequest.sendReadRequest();
}
"A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it. " # Source
Y is not an array so .push() won't work on it. # Source
To access the global scope through a string literal like you are trying you can use the window object which is the current global scope.
So in your case it would be window[y].push(id[i]);
Another option would be to change you scructure slightly as personally i don't like accessing the window directly.
so you could define your arrays like
var arrays = {
tes0: [],
tes2: [],
tes3: [],
tes4: [],
tes5: [],
}
and access them like:
arrays[y].push(id[i])
EDIT according to comments
So you want to access global variable in a loop. You are half way there. What your doing is building a string y which contains the property name then using that in the square brackets to access that property.
So with the window option that would be:
for(var z=0;z<5;z++ ){
var y="tes"+z;
for(var i = 0; i < id.length; i++)
window[y].push(id[i]);
}
}
or with the second object option
/*
Because arrays is an object we can use Object.keys
This will return an array of the keys in our object which we can loop over to access each one
*/
Object.keys(arrays).forEach(function(key) {
for(var i = 0; i < id.length; i++)
arrays[key].push(id[i]);
}
});
Hope that helps explain

Unable to .empty() the appended elements

state.on('change', function(){
city.empty();
$.getJSON("pincodes.JSON", function(pincodes){
var key = state.val();
for (var j= 0; j < pincodes['address'].length; j++) {
if (pincodes['address'][j]['circlename'] == key) {
temp.push(pincodes['address'][j]['regionname']);
}
}
cities = $.unique(temp);
for (var k = 0; k < cities.length; k++) {
city.append('<option>' + cities[k] + '</option>');
}
});
});
In the above state = $('#state') , the above works fine fills the cities on select "state" . But the issue is when a new state is selected the previously filled cities are also there . Even though I tried .empty on every change() .
You don't empty your temp array. So, every time this function is called, you keep appending items to your temp array.
You simply need to add the following line in your code:
state.on('change', function() {
city.empty();
temp = []; // <---
$.getJSON("pincodes.JSON", function(pincodes) {
What about cities = $.unique(temp);, it won't work.
According to jQuery.unique() documentation, this function
Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.
So, it is not a correct usage. If you get non-unique values from your JSON, you will need to use another way to get distinct values. There is a good SO article on this topic.

How to get the property value of an object using index in javascript?

I am creating multiple HTML elements.
Elements have different properties.
I would like to get the property name, and the its value using index.
var elements = [
{"type":"div","className":"items","id":"item-0-"+item}
{"type":"div","className":"items","id":"item-0-"+item}
{"type":"input","type":"number","step":1,"min":1}
];
I want to access it like,
alert(elements[0][1]); //"className":"items"
alert(elements[0][1].value); //items
I tried that but It is not working.
This should allow you to see everything:
var i, j, k;
for (i = 0; i < elements.length; i++) {
for (j in elements[i]) {
alert(i+' '+j+' is '+elements[i][j]);
console.log(i+' '+j+' is '+elements[i][j]); // This is less annoying than alerts
}
}
Take a look at Object.keys():
var name = Object.keys(elements[0])[1]; // Item name = 'classname'
alert(elements[0][name]); // Item value = 'items'

Appending Items from one array to each and every element of another array in Javascript

Note: I am not asking how to append data to an array!
Rather my problem is that I want to append items to each and every element of an array.
Here is a part of my code:
dataset=[];
var xpoints=["Jan","Feb","Mar","Apr","May"];
var ypoints=[10,20,30,40,50];
for (var i = 0; i < xpoints.length; i++) {
dataset.push({
x : xpoints[i],
y : parseFloat(ypoints[i])
});
}
The array so far would be as below:
dataset[0] - {x:Jan,y:10}
dataset[1] - {x:Feb,y:20}
dataset[2] - {x:Mar,y:30}
dataset[3] - {x:Apr,y:40}
dataset[4] - {x:May,y:50}
So far there is no problem...
But if now i have another array (Suppose that it is of the same length), I want to append the new array's elements into my existing array such that my output would be as follows:
var zpoints=["a","b","c","d","e"];
/*
Do something
*/
Required Output:
dataset[0] - {x:Jan,y:10,z:a}
dataset[1] - {x:Feb,y:20,z:b}
dataset[2] - {x:Mar,y:30,z:c}
dataset[3] - {x:Apr,y:40,z:d}
dataset[4] - {x:May,y:50,z:e}
If I do:
for (var i = 0; i < dataset.length; i++) {
dataset.push({
z:zpoints[i]
});
}
it would append it as different elements in the dataset array, which is not what I am looking for.
Is the required output achieveable using JavaScript? How?
What if I want to add multiple objects to the dataset array but I do not know the number of objects to be added while compiling?
Suppose that there can be multiples arrays:
z1=["a","b","c","d","e"];
z2=["l","m","n","o","p"];
z3=...
.
.
and so on.. and the number is unknown until runtime.
I want to do something like this:(invalid code)
for(var j=0;j<length;j++) //Length will be known only during runtime
for (var i = 0; i < dataset.length; i++) {
dataset[i].z[j] = zpoints[i]; //z[j] is invalid!!
}
I need to name the objects dynamically somehow. Is there a way to achieve this?
It's rather simple:
for (var i = 0; i < dataset.length; i++) {
dataset[i].z = zpoints[i];
}
A .push call will always append more entries to the array; in this case you want to modify the existing ones.
You need to simply add new property z to existing object:
var l = zpoints.length;
while(l --)
dataset[l].z = zpoints[l];

Function is rewriting variable. How is this possible?

This function seems to be rewriting the value for the 'pages' variable and I'm at my wit's end on this one.
I've tried returning the variable through a function, hardcoding the variable into the function, and a pile of other things, but this seems like it should work.
Any ideas?
EDIT:
The output from should be an array of objects formatted like this {default: "Tax Return", safe: "taxreturn"}. The function, when first called with getPages('Both', 'overview', null) and getPages('Both', null, 'overview') does this, but if you call it more times it will error and you will find that the 'pages' variable is now an array of objects.
var pages = [
"Dashboard",
"Overview",
"Contacts",
"Records",
"Cash Flow",
"Transactions",
"Income",
"Expenses",
"Tax Return"
];
var getPages = function(format, includeOne, excludeOne)
{
var pageStrings = pages;
if(includeOne)
for(var p = 0; p < pageStrings.length; p++)
if(uriSafe(pageStrings[p]) == uriSafe(includeOne))
pageStrings = [pageStrings[p]];
if(excludeOne)
for(var c = 0; c < pageStrings.length; c++)
if(uriSafe(pageStrings[c]) == uriSafe(excludeOne))
pageStrings.splice(c, 1);
var outputArray = [];
switch(format)
{
case 'UriSafe':
for(var i = 0; i < pageStrings.length; i++)
pageStrings[i] = uriSafe(pageStrings[i]);
break;
case 'Both':
for(var x = 0; x < pageStrings.length; x++)
{
pageStrings[x] = {
default: pageStrings[x],
safe: uriSafe(pageStrings[x])
};
}
break;
default:
}
function uriSafe(str)
{
return str.replace(' ', '').toLowerCase();
}
console.log(pageStrings);
return pageStrings;
}
var pageStrings = pages;
is creating a reference to the very same array object. When you access it via pageString, you alter the same object which pages does refer to. To create a copy of it (from which you then can splice, assign properties to, etc without altering pages), use
var pageStrings = pages.slice();
I think your confusion is around the following line
var pageStrings = pages;
This does not create a copy of pages it simply creates a reference to pages. This means any edit you make to the value of pageStrings (clearing, changing elements, etc ...) will show up on pages because they refer to the same variable.
If you want pageStrings to have a copy of the pages array then do the following
var pageStrings = pages.slice(0);
var pageStrings = pages; is your hangup. Keep in mind that when you use = in this way, your new var will be a reference if the argument on the right is and array, object, or function. With strings and numbers you will get the copy you were expecting.

Categories

Resources