Add JSON object to Dictionary Value - javascript

Hi i'm currently trying to do a function that will get a key(string)/value(JSON) pair from a dictionary stored at a database and add information about the player into a temporary JSON(playersInfo), then set that JSON object back to the value which i got earlier, i'm still very noob at javascript and i couldn't find the right syntax to do it.
If there's anything i can do to make myself clear please let me know.
Both Get...Data() functions return different dictionaries.
handlers.UpdateJackpotPlayers = function(args, context) {
var playersInfo = {};
var userData = server.GetUserData({
PlayFabId: currentPlayerId
});
var serverData = server.GetTitleInternalData();
playersInfo = JSON.parse(serverData.Data["jackpotPlayers"].Value);
playersInfo.PlayerId += JSON.parse(" / " + currentPlayerId);
playersInfo.PlayerName += JSON.parse(" / " +
userData.Data["PlayerName"].Value);
playersInfo.AchievedJackpot += JSON.parse(" / " + args);
server.SetTitleInternalData({
"Key": "jackpotPlayers",
"Value": JSON.stringify(playersInfo)
});
}

Related

Print Object like console.log (with a lot of information) in javascript

I need to send an email that contains the console.log output of a JS object. Here a code example:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
console.log(array_multi);
In my console result like this:
Is there some method to get this output in plain text, or should I write a custom parsing function?
If you are using JSON.stringify, you'll get the complete data, however there are a few downsides:
Arrays string properties, functions and other data structures get ignored completely (therefore serializing your data as is won't work¹)
circular references fail to serialize
There is no way to see inheritance from that
In your case you could do:
let array_multi = {};
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
// logs as object
console.log(array_multi);
console.log(typeof array_multi);
// parse and convert to string
console.log(JSON.stringify(array_multi));
console.log(typeof JSON.stringify(array_multi));
In Node.js you've got another option, which is util.format, which will return the same content as a string that you can see in the Node.js console. While it does give you a great insight into the different datatypes and relationships, it cannot show you the same infinite tree that an interactive console is able to show, so it will only show you a small part of the big picture.
¹: Your array_multi should actually be an object, not an array, as arrays should only have numeric keys.
After a lot of search the right method is write a custom function (chrome have once inside dev tools core)
here the solution:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
function print_js_element(elm, show_content = false){
let output_res = "{\n";
let object_keys = Object.keys(elm);
object_keys.some(function(key,index) {
output_res += "\t" + key + ": (" + elm[key].length + ")";
if(show_content){
output_res += " " + JSON.stringify(elm[key]);
}
output_res += "\n";
});
output_res += "\n}";
return output_res;
}
console.log(print_js_element(array_multi,false));
console.log(print_js_element(array_multi,true));
Covert this array into an object first:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
let arrObj = {...array_multi};
console.log(JSON.stringify(arrObj));

Node js merge values basic implemenation

I am trying to do something like the below but merge function has a problem with the line
content = content.replace( content, "Hi" + values.first_name + "! Thanks for completing this code challenge :)" );
Filename : app.js
var utilities = require("./utilities");
var mailValues = {};
mailValues.first_name = "Janet";
var emailTemplate = "Hi %first_name%! Thanks for completing this code challenge :)";
var mergedContent = utilities.merge(emailTemplate, mailValues);
//mergedContent === "Hi Janet! Thanks for completing this code challenge :)";
Filename : utilities.js
function merge(content, values) {
content = content.replace( content, "Hi" + values.first_name + "! Thanks for completing this code challenge :)" );
return content;
}
module.exports.merge = merge;
Your merge function is not good, it does a weird thing and will surely returns a weird string if you pass another template. You're replacing the entire input string by the "Hi...." string but with first_name inserted so in the end, your function is too specific and can't handle extra parameters or another template/string.
function merge(content, values) {
// loop over all the keys in the values object
Object.keys(values).forEach(function(key) {
// look for the key surrounded by % in the string
// and replace it by the value from values
content = content.replace('%' + key + '%', values[key]);
});
return content;
}
var mailValues = {};
mailValues.first_name = "Janet";
mailValues.last_name = "Doe";
var emailTemplate = "Hi %first_name% %last_name%! Thanks for completing this code challenge :)";
var mergedContent = merge(emailTemplate, mailValues);
document.write(mergedContent);
Try the "run code snippet" button.
for ... in version, for information, better to use the previous version.
function merge(content, values) {
// loop over all the keys in the values object
for (var key in values) {
// look for the key surrounded by % in the string
// and replace it by the value from values
content = content.replace('%' + key + '%', values[key]);
}
return content;
}
var mailValues = {};
mailValues.first_name = "Janet";
mailValues.last_name = "Doe";
var emailTemplate = "Hi %first_name% %last_name%! Thanks for completing this code challenge :)";
var mergedContent = merge(emailTemplate, mailValues);
document.write(mergedContent);

Assign an array value to another array called dynamically

I've got an array like this
pages['name'] = "Home";
pages['childs'][0]['name'] = "Sub page 1";
pages['childs'][1]['name'] = "Sub page 2";
pages['childs'][2]['name'] = "Sub page 3";
pages['childs'][2]['childs'][0]['name'] = "Sub sub page 1";
My problem is that I need to change portions of the array for example.
pages['childs'][0] = otherarray;
// or
pages['childs'][2]['childs'][0] = otherarray;
Obviously if otherarray was a string I can easily do something like
eval('pages' + where + ' = "' + stringvalue + '"');
But I've an array as value so I can't do
eval('pages' + where + ' = "' + otherarray + '"');
because the code executed will be
pages['childs'][0] = [object object];
What's the solution? Thanks
Rather than screw around with eval and stringifying things, you should just build an accessor. Many would agree that using eval like this is just bad practice in every way. I don't know if combining it with stringify makes it worse, but it certainly feels dirty.
Here's a basic, fairly stupid accessor, but it should give you the idea.
// Arguments: array to modify; new value; series of nested array keys.
function modifyArray(base, value){
var refObj = base;
for (var ii=2, max=arguments.length; ii < max; ii++){
if (!refObj) {
return false; // we supplied an invalid key.
}
if (ii == max-1){
refObj[arguments[ii]] = value;
return true;
}
refObj = refObj[arguments[ii]];
}
return false; // probably forgot to include keys.
}
modifyArray(pages, otherarray, 'childs', 2, 'childs', 0);
http://jsfiddle.net/2ts78brg/
For me this solution works
eval("pages" + where + " = JSON.parse('" + JSON.stringify(otherarray) + "')");
It sounds more like a workaround then a solution but it works and for me it's enough.

Loading an array from local storage: result not an array - javascript [duplicate]

This question already has answers here:
How to store objects in HTML5 localStorage/sessionStorage
(24 answers)
Closed 8 years ago.
I have several large multi-dimensional arrays that I'm saving to local storage. They look like this:
[[[-150],[0],[-650],0],[[-100],[0],[-650],0],[[-50],[0],[-650],0] ... ]
The data is '4D' data. When I try loading this 'string' into an array in another JS (in separate html), it doesn't behave like an array- it's only a string.
Here's how I load the data back into the second JS (not sure why the loop didn't work either):
var lay= new Array();
//for(var g=0;g>=9;g++)
//{ lay[g] = localStorage.getItem("key" + g);
// console.log(lay[g]);
//}
lay[0] = localStorage.getItem("key0");
lay[1] = localStorage.getItem("key1");
lay[2] = localStorage.getItem("key2");
//... more here
lay[9] = localStorage.getItem("key3");
After I load this "4D" info into the array, I pull the info out to use it:
var count=0;
var len=0;
for (y=0;y<=1;y++)
{ console.log(lay[y]);
count=1;
len = lay[y].length;
for (x=1;x<=len-1;x++)
{
Rx = lay[y][count][0];
Ry = lay[y][count][1];
Rz = lay[y][count][2];
Rcolor = lay[y][count][3];
When I add this to the code console.log(len); I get the length of characters in the array, not the number of elements. How can I get the data from local storage to come in and behave like array? I thought that the formatting alone would get it behave like an array.
Do I need to parse it back into an array again? If so, I'm guessing I should just output the data in a simpler format to parse it again...
Thanks for the help!
Edit
Here's how I made the local storage:
for (var a=0;a<=14;a++)
{ updateTemp(tStep + a);
$("#temp tbody tr").each(function(i, v){
data[i] = Array();
$(this).children('td').each(function(ii, vv){
data[i][ii] = $(this).text();
rows=ii;
cols=i;
});
});
retval="";
for (var q=0;q<=cols;q++)
{
for (var w=0;w<=rows;w++)
{
var tempv = data[q][w];
var tX = w*50 - 1000;
var tY = 1*50 - 50;
var tZ = q*50 - 1000;
if (tempv==-9){
(dummy=q*w);
}
else {retval += tX +',' + tY + ',' + tZ + ',' + tempv + ',';}
}
}
var kee = "key" + a;
retval = retval.substring(0, retval.length-1); //this is to get rid of the last character which is an extra ,
window.localStorage.setItem(kee, retval);}
JSON encode the array before storing, parse after retrieving.
localStorage.test = JSON.stringify([1,2,3]);
console.log(JSON.parse(localStorage.test));
This is a duplicate of “Storing Objects in HTML5 localStorage”. localstorage only handles strings. As suggested there, serialise your array to a JSON string before storing.

using localStorage to keep a count

var nicWinsVsMac;
if (tempresult === win) {
wincount = JSON.parse(localStorage.getItem (playerName + 'wincount'));
wincount += 1;
localStorage.setItem(playerName + 'wincount', wincount);
winsvsopponent = 'WinsVs' + opponent;
winsvsopponent = JSON.parse(localStorage.getItem(playerName + 'WinsVs' + opponent));
winsvsopponent += 1;
console.log(winsvsopponent);
localStorage.setItem(playerName + 'WinsVs' + opponent, 'winsVs' + opponent);
console.log(localStorage.getItem(nicWinsVsMac));
}
playerName and opponent are parameters passed in. In this case, playerName = 'nic' and opponent = "Mac"
My browser is giving me "unexpected token w" on the line where i parse out the localStorage. I cannot figure out what is going on. Any help would be great. Thanks!
Instead of using a separate localStorage variable for each attribute of the player. Why not store all the players attributes in a single object and then save that to localStorage.
For example, you can do the following:
var player = new Object();
player.name = 'Mac';
player.winCount = 3;
player.winAgainst = new Array();
localStorage.setItem(player.name, JSON.stringify(player));
var player1 = JSON.parse(localStorage.getItem(player.name));
console.log(player1.name + " has " + player1.winCount + " wins.");
This allows you to save all the player's attributes to a single localStorage variable making it much easier to read and write from.
In regards to the error you are recieving, I believe the issue with your code is that you are not using JSON.stringify in the call to setItem.

Categories

Resources