CasperJS array.push Making Variables Null - javascript

I have a custom data type that I am populating, I have verified that data populates correctly but when I try to push it to an array the result is both the array and the custom data type variable are null. Here is an example of what I am doing:
var values = [];
var temp = {};
temp['one'] = rows[i].cells[1].innerText.trim();
temp['two'] = rows[i].cells[2].innerText.trim();
temp['three'] = rows[i].cells[3].innerText.trim();
temp['four'] = rows[i].cells[4].innerText.trim();
values.push(temp);
When I output temp before values.push(temp); all expected values are present. When outputting either values or temp after values.push(temp); both are null.
Very confused, any help is appreciated.

Declare array and object like this..
var values = [];
var temp = {};
Example:
var values = [];
var temp = {};
temp['one'] = 'one';
temp['two'] = 'two';
temp['three'] = 'three';
temp['four'] = 'four';
values.push(temp);
console.log(values);

This was a dumb mistake on my part, nothing to do with the .push but want to answer for anyone else having the problem.
var values = [];
Was declared outside of any function, I thought I could do this and it would be global but that was a newbie mistake.

Related

Specifying a variable as an array destination in Javascript ( mutability? ) [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 2 years ago.
I have 5 arrays in Javascript that I’ll fill and whichever array I fill will depend on the value of “x”. I am getting hopelessly confused regarding variable usage/mutability here. My code is below….
//Node arrays that hold the IDs of each node
nodeOne = [];
nodeTwo = [];
nodeThree = [];
nodeFour = [];
nodeFive = [];
var nodesButtonToNode = {pn_btn_1:"nodeOne", pn_btn_2:"nodeTwo", pn_btn_3:"nodeThree", pn_btn_4:"nodeFour", pn_btn_5:"nodeFive"};
x = "pn_btn_1";
nodesButtonToNode.x.push("I am supposed to go into nodeOne")
In a nutshell if x = “pn_btn_1” that would then pull the value of the array that needs to be filled by specifying the key in nodesButtonToNode. In this case that array would be nodeOne. If x = “pn_btn_2” then the area that would need to be added to would be nodeTwo. As expected I am getting lots of undefined errors and I'm not sure where I'm going wrong.
Many TIA for any pointers
You should use an object with the array names as the keys, then you can access them via bracket obj[var] notation:
//Node arrays that hold the IDs of each node
const nodes = {
nodeOne: [],
nodeTwo: [],
nodeThree: [],
nodeFour: [],
nodeFive: []
};
var nodesButtonToNode = {
pn_btn_1: "nodeOne",
pn_btn_2: "nodeTwo",
pn_btn_3: "nodeThree",
pn_btn_4: "nodeFour",
pn_btn_5: "nodeFive"
};
x = "pn_btn_1";
nodes[nodesButtonToNode[x]].push("I am supposed to go into nodeOne");
console.log(nodes);
Your nodesButtonToNode should use the actual arrays rather than their names.
var nodesButtonToNode = {
pn_btn_1: nodeOne,
pn_btn_2: nodeTwo,
pn_btn_3: nodeThree,
pn_btn_4: nodeFour,
pn_btn_5: nodeFive
};
This will let you update the arrays directly.
Also, the value of x isn't in your mapping it should be pn_btn_1
//Node arrays that hold the IDs of each node
nodeOne = [];
nodeTwo = [];
nodeThree = [];
nodeFour = [];
nodeFive = [];
var nodesButtonToNode = {
pn_btn_1: nodeOne,
pn_btn_2: nodeTwo,
pn_btn_3: nodeThree,
pn_btn_4: nodeFour,
pn_btn_5: nodeFive
};
x = "pn_btn_1";
nodesButtonToNode[x].push("I am supposed to go into nodeOne");
console.log(JSON.stringify(nodeOne));
You have some errors in your syntax, check out example
const nodeOne = [];
const nodeTwo = [];
const nodeThree = [];
const nodeFour = [];
const nodeFive = [];
const nodesButtonToNode = {
pn_btn_1: nodeOne,
pn_btn_2: nodeTwo,
pn_btn_3: nodeThree,
pn_btn_4: nodeFour,
pn_btn_5: nodeFive
};
const x = "pn_btn_1";
nodesButtonToNode[x].push("I am supposed to go into nodeOne");
console.log(nodesButtonToNode);

How to set hash key dynamically in javascript

With this code,
h = {}
for (var i in [0,1]){ h[i.ToString] = i; }
I expected same result with h["1"] = 1 and h["2"] = 2.
Why is this code doesn't work, and how can I define hash key dynamically in javascript?
The for .. in loop in JS iterates over keys, not over values (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in).
So in your case, you iterate over the keys of the array you have in there.
Those will be 0, 1, 2 ... no matter what you put in there.
What you could do instead would be something like this:
var obj = {};
var data = [1,2,3,4];
data.forEach(function(val) {
obj[val] = val;
});

Stringify with multidimensional array gives empty result

I have an array like this:
var d = new Array();
d[0] = new Array();
d[0]['item1'] = '123';
d[0]['item2'] = '456';
d[0]['item3'] = '789';
d[1] = new Array();
d[1]['item1'] = '123';
d[1]['item2'] = '456';
d[1]['item3'] = '789';
When using console.log(JSON.stringify(d)); my console logs "[[],[]]"
Why does JSON.stringify() give an empty result?
Here's a jsFiddle showing my current situation
I read this. The answer is a solution, however my attribute names are variable, as you can see in the jsFiddle. Is there a way to make an attribute's name variable? Like this (doesn't work obviously):
var s = 'attrName';
var object = {
s: '123'
}// The object should have an attribute named attrName
Try:
d[0] = {};
instead of:
d[0] = new Array();
This way d[0] is an object and not an array.
Working example: http://jsfiddle.net/FLDfR/
This is happening because you are confusing arrays and objects.
While it is true that in JavaScript, arrays are just special objects but they are treated somewhat differently.
While this isn't technically true, pretend that arrays can only take integer keys, between 0 and 2^53.
// Tested in the console.
var d = [];
d[0] ={};
d[0]['item1'] = '123';
d[0]['item2'] = '456';
d[0]['item3'] = '789';
d[1] = {};
d[1]['item1'] = '123';
d[1]['item2'] = '456';
d[1]['item3'] = '789';
alert(JSON.stringify(d));
will do what you want.
Going along with Jeremy J Starcher, you could just go full object with it:
var data = {
'0': {
'item1': '123'
},
'1': {
'item1': 'abc'
}
};
This will give you a better outcome, though not technically an array. =/
To make the dynamic attribute you can use [] something like
var s = 'attrName';
var object = {};
object[s] = '123';
DEMO

Push an object into the object list object

The simplest question ever, and I did not find right answer yet.
Got object list: object_list = {}
Got object: object_x = {...}
How do I add object_x to object_list[objects_x]?
I tried: object_list[objects_x][object_list[objects_x].length] = object_x, but object_list[objects_x].length is undefined.
push() does not work either.
Do I really need to define external counter for that?
PLEASE NOT THAT I MEAN LIST OF LISTS OF OBJECTS. NOTE THE DIFFERENCE BETWEEN objects_x and object_x.
There is no simple solution like in PHP where you simply $array['something'][] = $somedata ?
object_list['object_x'] = object_x;
// or
object_list.object_x = object_x;
console.log(object_list.object_x === object_list['object_x'])
How to work with objects - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
When you create a variable like var stuff = {}, you're creating an empty object literal, it has no attributes (properties or methods) other than what it inherits from Object. If you want to keep objects stored in various lists in this object you need to first create those lists.
var stuff = { shelves: [], selectors: [], images: [], additional: [] };
Now you can add whatever you want to those lists as much as you want.
var image = { src: '/path/to/image.jpg' };
stuff.images.push(image);
You can add more lists to stuff whenever like by just setting the new property on stuff.
stuff.some_other_list = []
Hope it helps.
Your base assumption is wrong.
This:
var object_list = {}
Is not a list. It's not an array and you can't reference its items by index, thus it also does not have .length property.
What you are after is a plain array:
var object_list = [];
Now you can push items into it:
object_list.push(object_x);
Edit: based on your comments and edits, I think what you're really after are couple of helper functions:
function AddToList(list, item) {
var counter = 0;
for (var key in list)
counter++;
var key = "item_index_" + counter;
list[key] = item;
}
function GetItemByIndex(list, index) {
var counter = 0;
var existingKey = "";
for (var key in list) {
if (counter == index) {
existingKey = key;
break;
}
counter++;
}
return (existingKey.toString().length > 0) ? list[existingKey] : null;
}
Having those, you can have such a code now:
var mainList = {};
var newItem = { "foo": "bar" };
AddToList(mainList, newItem);
var dummy = GetItemByIndex(mainList, 0)["foo"]; //will contain "bar"
Live test case.
If you are interested use object, not array, you can use like this:
var object_list = {};
var object_x = {'prop1':'val1'};
// add object
object_list.myobj = object_x;
// for access, same scheme.
object_list.myobj.prop1 = 'valX';
// for loop thru
for (var key in object_list) {
var obj = object_list[key];
obj.prop1 = 'valY';
}

JSON.stringify(object) incorrect

Sorry for my last question being so confusing, I was confused my self, but now I got a proper example:
var obj = {};
obj.entities = [];
obj.entities["player"] = [];
obj.entities["player"]["0"] = [];
obj.entities["player"]["0"]["pos"] = "0,0";
var jsonStr = JSON.stringify(jsonObj);
// {"entities":[]}
console.log(JSON.stringify(obj));
The output of JSON.stringify(obj) is wrong as you can see.
What causes this ?
You're first building an array ([]), then assigning properties to it with non-number keys (player). This is technically possible (as in not causing an error), but it's not what arrays are for.
You should use objects ({}) instead. Also, ["player"] is the same as .player.
var obj = {};
obj.entities = {};
obj.entities.player = []; // array here because you're filling with indices ([0])
obj.entities.player[0] = {}; // object again, because non-indices as keys (`pos`)
obj.entities.player[0].pos = "0,0";
Objects can take any property key. Arrays are a subset of objects, which should only have indices (numbers >= 0) as keys.
Your life would be much easier if you'd define your objects in JSON to begin with:
var obj = {
'entities': [
{'player':{'pos': '0,0'}}
]
};
You're using named array indeces instead of object key/value pairs.
var obj = {};
obj.entities = {};
obj.entities["player"] = {};
obj.entities["player"]["0"] = [];
obj.entities["player"]["pos"] = "0,0";
// {"entities":{"player":{"0":[],"pos":"0,0"}}}
console.log(JSON.stringify(obj));
entities, and entities["player"] and entities["player"]["0"] need to be objects, not arrays.
You're adding properties to these arrays, rather than pushing values onto them. These custom properties are not getting stringified.
The fix is simple:
var obj = {};
obj.entities = {}; // <------------ this is an object now
obj.entities["player"] = {}; // <--------- also an object
obj.entities["player"]["0"] = {}; // <-------- and so on
obj.entities["player"]["0"]["pos"] = "0,0";
I think you have some serious confusions about arrays and objects in javascript. An array ([]) works only with positive integer indexes. In your example you are doing the following:
obj.entities = [];
obj.entities["player"] = [];
You say that obj.entities is an array and then you use player as index. And player is not an integer. So this code makes no sense. On the other hand you could use objects with properties. Those properties can be strings:
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = 'foo bar';
You are confusing objects with arrays. The following code will work.
var obj = {};
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = {};
obj.entities.player[0].pos = "0,0";
The things you went wrong:
An array can have only integer indexes. So it's incorrect writing a["1"] if you intend to use a as an array.
To be correctly serialized, only an object can have named properties, like object.entities.player or object.entities["player"].

Categories

Resources