Why this json swap code does not work? - javascript

I have this fun :
swapjson = function (j1,j2)
{ var jj = JSON.parse(JSON.stringify(j1));
j1 = JSON.parse(JSON.stringify(j2));
j2 = jj;
}
I have also:
var myjson1 = {'x':1000, 'y':1000};
var myjson2 = {'x':2000, 'y':-2000};
swapjson (myjson1,myjson2);
console.log myjson1.x
1000 ?????
And I discover that inside the swapjson function the swap is made but not after call.
What is happen ? I dont understand what I'm doing bad...
Any help would be appreciated.

You can't replace the entire object like that, as the object itself isn't passed by referenced.
You can however change properties of the object passed, and it will stick, as a copy of the object is passed in.
So instead of parsing to strings and back to objects you can just iterate over the two objects keys, and replace one by one
swapjson = function (j1, j2) {
var temp = {};
for (key in j1) {
temp[key] = j1[key];
delete(j1[key]);
}
for (key in j2) {
j1[key] = j2[key];
delete(j2[key]);
}
for (key in temp) {
j2[key] = temp[key];
}
}
FIDDLE

You copy the value of myjson1 (which is a reference to an object and nothing to do with JSON) into j1, and the value of myjson2 into j2.
Then you overwrite the value of j1 and the value of j2.
You never change the values of myjson1 or myjson2.

Related

adding object to array using .splice()

I have a problem adding the object "myobj" to the arrays data / data2. As you see "myobj" a JS object which I would like to add to either data or data2. the functions are being triggered by clicks on different buttons.
console.log of myobj shows me
{ array: "arr_id_1", axis: "x", acc: "", vel: "", dist: "", jerk: "" }
I receive an error saying data2.splice() is not a function.
which is the format I need. "myobj" is supposed to be added to an array which I want to use JSON.stringify on. This JSON literal goes then to a python script via ajax. The array "data" is being filled with each click I perform correctly but not in the format for further processing. So I tried to fill array data2 since I have read that I could use .splice() as well. Unfortunately, console.log(data2) shows "undefined" for each field I try to fill and I have no idea how to solve it.
I tried to use JSON.stringify on "myobj" and as another attempt, I have tried to JSON.parse it back again. I tried adding the brackets and colons into quotes but no success either.
I am grateful for any advice or help.
var counterx = 0;
let data = [];
let data2 = {};
function valuesX() {
counterx++;
// does something here
let arr_id = [];
arr_id.name = 'arr_id_' + counterx;
let ind = counterx - 1;
let myobj;
function arr() {
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value, btns.value, btnj.value)
myobj = {
array: arr_id[0],
axis: arr_id[1],
acc: arr_id[2],
vel: arr_id[3],
dist: arr_id[4],
jerk: arr_id[5]
};
console.log(arr_id.name, arr_id)
console.log(myobj)
console.log(data.name, data)
console.log(data2.name, data2)
}
data.name = 'data';
data2.name = 'data2';
data.splice(ind, 0, arr_id)
data2.splice(ind, 0, myobj)
}
SOLUTION:
I have converted the myobj to an object using Answer from JVE999, first suggestion and used .splice() to add the every new myobj to the array data. I have used splice because I need to overwrite already existing elements while keeping the order (Thus the indx) when I trigger the function (.splice() reference).
var arr_id = [];
arr_id.name = 'arr_id_'+counterx;
var myobj;
var indx = counterx-1;
var data_new;
data.name = 'data';
function arr(){
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value,btns.value, btnj.value)
myobj = {
array:arr_id[0],
axis:arr_id[1],
acc:arr_id[2],
vel:arr_id[3],
dist:arr_id[4],
jerk:arr_id[5]
};
data_new = convArrToObj(myobj);
data.splice(indx, 1, data_new)
data_str = JSON.stringify(data)
console.log(data.name, data)
console.log(data_str)
}

Create variables based on array

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Ƃ

Modify a global variable based on an object property

I'm trying to learn object oriented javascript and ran into the following problem:
I have an object constructor (is that the right term?) like this:
function itemCreator(itemName, itemType, itemPositionX, itemPositionY) {
this.itemName = itemName;
this.itemType = itemType;
this.itemPositionX = itemPositionX;
this.itemPositionY = itemPositionY;
allItems.push(this); //store all items in a global variable
}//end itemCreator;
//then I use it to create an object
megaRocket = new itemCreator (
'megarocket',
'item_megarocket',
108,
475
)
Now I realised I also need to map these objects to modify different global variables based on which "itemType" the object has. This is where I am stuck. How can I make a global variable that only objects with a specific itemType property can modify?
For example I would like to create an object that increments a variable called amountOfMegarockets, but only if the itemType for that object is "item_megarocket".
I later plan on looping an array of these items to see if player object touches them (to collect the item):
function checkForItems(){
var itemLen =allItems.length;
for (i=0; i < itemLen; i++){
var itemObject = allItems[i];
if ( //checking for "collisions" here
(ship.x < (itemObject.itemBitmap.x + itemObject.size) && (ship.x + shipWidth) > itemObject.itemBitmap.x) &&
(ship.y < (itemObject.itemBitmap.y + itemObject.size) && (ship.y + shipWidth) > itemObject.itemBitmap.y)
){
itemObject.actor.y = -500; //just removing the item from canvas here (temporary solution)
// Here comes pseudo code for the part that I'm stuck with
variableBasedOnItemObject.itemType++;
}
I hope my explanation makes sense to someone!
EDIT:
Bergi's answer makes most sense to me, but I can't get the syntax right. Here's how I'm trying to use Bergi's code:
var amounts = {},
allItems = [];
function itemCreator(itemName, itemType, itemPositionX, itemPositionY) {
this.itemName = itemName;
this.itemType = itemType;
this.itemPositionX = itemPositionX;
this.itemPositionY = itemPositionY;
(amounts[itemType]=2); // this is different from bergi's example because I need to set the initial value of the item to two
//I also shouldn't increase the item amount on creation of the item, but only when it's specifically called from another function
this.increaseCount = amounts[itemType]++; //this should IMO increase the itemType amount inside the amounts object when called, but it doesn't seem to work
}
//creating the object the way bergi suggested:
allItems.push(new itemCreator('shootUp001', 'item_up', 108, 475));
Now here's the problematic part:
function checkForItems(){
var itemLen =allItems.length;
for (i=0; i < itemLen; i++){
var itemObject = allItems[i];
if ( my condition here)
){
//code below is not increasing the value for the current itemType in the amounts object.
//Probably a simple syntax mistake?
itemObject.itemType.increaseCount;
}
}
}
Why is my call of itemObject.itemType.increaseCount; not increasing the value of amounts.itemType?
Increment a global variable called amountOfMegarockets, but only if the itemType for that object is "item_megarocket".
Don't use a global variable for each of those item types. Do use one object (in global or local scope) which counts the amouts of each type on its properties.
var amounts = {},
allItems = [];
function Item(itemName, itemType, itemPositionX, itemPositionY) {
this.itemName = itemName;
this.itemType = itemType;
this.itemPositionX = itemPositionX;
this.itemPositionY = itemPositionY;
amounts[itemType]++ || (amounts[itemType]=1); // count by type
allItems.push(this); // store all items
}
Notice that I wouldn't put all Item instances in an array by default, better omit that line and let it do the caller:
allItems.push(new Item('megarocket', 'item_megarocket', 108, 475));
you can do some things like
(function (global) {
// create a scope
var allItems = [];
global.itemCreator = function(itemName, itemType, itemPositionX, itemPositionY) {
this.itemName = itemName;
this.itemType = itemType;
this.itemPositionX = itemPositionX;
this.itemPositionY = itemPositionY;
allItems.push(this); //store all items in a global variable
}//end itemCreator;
})(this);
this will work. but seriously dont complicate too mutch your code juste to make private var. if someone want to cheat using debugger he will always found a way to do it.
---- edit
If you juste want access to global var base on itemType you can do some thing like:
function checkForItems(){
var itemLen =allItems.length;
for (i=0; i < itemLen; i++){
var itemObject = allItems[i];
if ( //checking for "collisions" here
(ship.x < (itemObject.itemBitmap.x + itemObject.size) && (ship.x + shipWidth) > itemObject.itemBitmap.x) &&
(ship.y < (itemObject.itemBitmap.y + itemObject.size) && (ship.y + shipWidth) > itemObject.itemBitmap.y)
){
itemObject.actor.y = -500; //just removing the item from canvas here (temporary solution)
// Here comes pseudo code for the part that I'm stuck with
if (window[itemObject.itemType + "Data"])) {
variableBasedOnItemObject.itemType++;
} else {
window[itemObject.itemType + "Data"] = {
itemType: 1
}
}
}
}
}

JavaScript stop referencing object after pass it to a function

I know JavaScript passes Objects by reference and thus I'm having a lot of trouble with the following code:
function doGradeAssignmentContent(dtos) {
var x = 5;
var allPages = [];
var stage = new App.UI.PopUpDisplay.PopUpStageAssignmentGrader(null, that);// pass launch element
for(var i = 0; i < dtos[0].result.students.length; ++i) {
var pagesSet = [];
for(var j = 0; j < dtos[0].result.questions.length; ++j) {
var questionObject = jQuery.extend(true, {}, new Object());
questionObject = dtos[0].result.questions[j];
if(dtos[0].result.students[i].answers[j].assignmentQuestionId === questionObject.questionId) {// expected, if not here something is wrong
questionObject.answer = dtos[0].result.students[i].answers[j].studentAnswer;
questionObject.pointsReceived = dtos[0].result.students[i].answers[j].pointsReceived;
} else {
var theAnswer = findAssociatedStudentAnswer(questionObject.questionId, dtos[0].result.students[i].answers[j]);
if(theAnswer !== null) {
questionObject.answer = theAnswer.studentAnswer;
questionObject.pointsReceived = theAnswer.pointsReceived;
} else {
alert("Unexpected error. Please refresh and try again.");
}
}
pagesSet[pagesSet.length] = new App.UI.PopUpDisplay.StageAssignmentGradingPages[dtos[0].result.questions[j].questionType.charAt(0).toUpperCase() + dtos[0].result.questions[j].questionType.slice(1) + "QuestionAssignmentGradingPage"](j + 1, questionObject);
}
var studentInfo = {};
studentInfo.avatar = dtos[0].result.students[i].avatar;
studentInfo.displayName = dtos[0].result.students[i].displayName;
stage.addPageSet(pagesSet, studentInfo);
}
stage.launch();
}
First let me show you what the result (dtos) looks like so you can better understand how this function is parsing it:
The result (dtos) is an Object and looks something like:
dtos Array
dtos[0], static always here
dtos[0].result, static always here
dtos[0].questions Array
dtos[0].questions.index0 - indexN. This describes our Questions, each one is an Object
dtos[0].students Array
dtos[0].students[0]-[n].answers Array. Each student array/Object has an Answers array. Each student will have as many elements in this answers Array that there were questions in dtos[0].questions. Each element is an Object
Now what we do in this here is create this Object stage. Important things here are it has an array called "this.studentsPages". This array will ultimately have as many entries as there were students in dtos[0].students.
So we loop through this for loop disecting the dtos array and creating a pagesSet array. Here comes my problem. On the first iteration through the for loop I create this questionObject element. I also have tried just doing var questionObject = {}, but what you see now was just an attempt to fix the problem I was seeing, but it didn't work either.
So at the end of the first iteration of the outer for loop I call stage.addPageSet, this is what happens here:
var pageObject = [];
pageObject["questions"] = pageSet;
pageObject["displayName"] = studentInfo.displayName;
this.studentsPages[this.studentsPages.length] = pageObject;
if(this.studentsPages.length === 1) {// first time only
for(var i = 0; i < pageSet.length; ++i) {
this.addPage(pageSet[i]);
}
}
The important thing to take notice of here is where I add pageObject on to this.studentsPages which was an empty array before the first call. pageObject now has pageSet plus a little bit more information. Remember, pageSet was an Object and thus passed by reference.
On the next iteration of the for loop, when I hit this line:
questionObject.answer = dtos[0].result.students[i].answers[j].studentAnswer;
It goes wrong. This changes the local copy of questionObject, BUT it also changes the copy of questionObjec that was passed to addPageSet and added to the studentsPages array in the first iteration. So, if I only had 2 students coming in, then when all is said and done, studentsPages hold 2 identical Objects. This should not be true.
The problem is questionObject in the doGradeAssignmentContent function is keeping a reference to the Object created on the previous iteration and then overrides it on all subsequent iterations.
What can I do to fix this?
Thanks for the help!
With out having looked at it too closely I believe you need to change the following:
// Before:
var questionObject = jQuery.extend(true, {}, new Object());
questionObject = dtos[0].result.questions[j];
// After:
var questionObject = jQuery.extend(true, {}, dtos[0].result.questions[j]);
I didn't look too closely if there are other instances in the code where this needs to be applied, but the core concept is to utilize jQuery's deep copy to generate a duplicate of the object you do not wish to retain a reference to.

Javascript pass by object by reference then update

I've been searching all over SO and I know there are a lot of topics about this but I haven't found one that answered my question.
I saw a question about getting an object value back from a string like this:
function getPropertyByString(str) {
var properties = str.split(".");
var myTempObject = window[properties[0]];
for (var i = 1, length = properties.length; i < length; i++) {
myTempObject = myTempObject[properties[i]];
}
return myTempObject;
}
So if there is a global variable called myGlobalVar, you could pass the string 'myGlobalVar.someProp.stateName' and assumming that is all valid you would get back the value of stateName say Arizona for example.
How could I update that property to California now?
If I try
var x = getPropertyByString('myGlobalVar.someProp.stateName');
x = 'California';
that will update the value of x and not the object.
I tried
var x = getPropertyByString('myGlobalVar.someProp.stateName');
x.value = 'California';
that didn't work either.
Can someone please help me to understand this with my example?
Thanks
Try the following;
function setPropertyByString(path, value) {
var steps = path.split("."),
obj = window,
i = 0,
cur;
for (; i < steps.length - 1; i++) {
cur = obj[steps[i]];
if (cur !== undefined) {
obj = cur;
} else {
break;
};
};
obj[steps[i]] = value;
}
It'd work by using it such as;
setPropertyByString('myGlobalVar.someProp.stateName', 'California');
You can see it in action here; http://jsfiddle.net/xCK8J/
The reason yours didn't work is because strings are immutable in JavaScript. You are re-assigning the variable x with the value 'California', rather than updating the location it points to to be 'California'.
If you'd have done;
var x = getPropertyByString('myGlobalVar.someProp');
x.stateName = 'California';
You'd see it works; as you're manipulating the object pointed to by x, rather than reassigning x to be something else. The above is what the setPropertyByString() method does behind the scenes; it just hides it from you.
This would do the trick:
myGlobalVar.someProp.stateName = "California"
So would this:
myGlobalVar["someProp"].stateName = "California"
or this:
myGlobalVar["someProp"]["stateName"] = "California"
Alternatively,
var x = getPropertyByString('myGlobalVar.someProp');
x.stateName = "California"
Note that if, in my last example, I do something like this:
x = {stateName:"California"};
It will not change the value of myGlobalVar.someProp.stateName.
Using = assigns a new value to the variable on the LHS. This is not the same thing as assigning a new value to the referent of the variable.

Categories

Resources