I am using javascript to create a message queue, say for example I want to store the messages "hello" and "word" to user with id "123", I am using the following to set and retrieve them.
var messages = [];
var userId = 123;
messages[userId].push("hello");
messages[userId].push("word");
needless to say, this is not working, damn arrays! How can I make this work, keeping it as simple as possible?
Thanks in advance
You need an array ([]) for every user:
var messages = {};
var userId = 123;
messages[userId] = ["hello", "word"];
You can use push too:
var messages = {};
var userId = 123;
messages[userId] = [];
messages[userId].push("hello");
messages[userId].push("word");
messages[userId] does not exist.
You need to put an array there:
messages[userId] = [];
well, technically you could push elements as properties of an object, which you have created and then iterate thorugh its properties.
Related
SOLVED, Thank you! I needed to specify the index.
I am trying to push a set of variables into an array from user input.
Without using push it is working fine;
var inputStart = addAppointment.inputStart.value;
var inputEnd = addAppointment.inputEnd.value;
var appointmentArr = [];
appointmentArr = {start:inputStart, end:inputEnd};
document.write(appointmentArr.start);
document.write(appointmentArr.end);
however, when I try to push the variables it returns undefined;
var inputStart = addAppointment.inputStart.value;
var inputEnd = addAppointment.inputEnd.value;
var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});
document.write(appointmentArr.start);
document.write(appointmentArr.end);
Can anyone explain why this is happening?
As far as I am aware I need to use push because I eventually want to create a new, populated index number every time the user inputs data, so any help is greatly appreciated.
Thanks in advance
You are accessing array.
So, the document.write part should be like this
document.write(appointmentArr[0].start);
document.write(appointmentArr[0].end);
Since appointmentArr is an array, you should fisrt take appointmentArr[0] to access the first element of the array.
After you push the value, the appointmentArr becomes, [{start:inputStart, end:inputEnd}]
Since, it is an array you cannot access object keys directly, you have to take specific index element and then can access them using appointmentArr[index]
var inputStart = 'inputStart';
var inputEnd = 'inputEnd';
var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});
document.write(appointmentArr[0].start + ' ');
document.write(appointmentArr[0].end);
Please run the above snippet
You re-assigned your variable as Object.
var appointmentArr = [];
appointmentArr = {start:inputStart, end:inputEnd};
This code overwrite appointmentArr from Array [] to Object { start:inputStart, end:inputEnd }
And in the second code:
var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});
You modify appointmentArr from Array [] to Array [ {start:inputStart, end:inputEnd} ].
So, following code will work as you want.
document.write(appointmentArr[0].start);
document.write(appointmentArr[0].end);
I am looking for some help, I am working on a piece of code for a client, the client currently have their analytics tag hardcoded to the page with all the key values being sent.
We are in the process of converting them to a new analytics platform using a tag management system, they have been able to update the majority of their platforms to create an object that the new analytics platform can reference but as this site is managed by a 3rd party they are unable to get this resolved in time for our release.
I have managed to successfully pull the tag and split the tag in to parameters:
var x = $('img[alt="MI_TAG"]').attr("src");
x.split("&");
Which creates the array:
1:"109=jsp.searchFlights.initial"
2:"117=Flight Only Journey"
3:"206=02/11/2017"
4:"208=03/11/2017"
5:"212=ALL"
What I want to do is take these array strings to create an object call "mi", like so:
109:"jsp.searchFlights.initial"
117:"Flight Only Journey"
204:""
205:""
206:"02/11/2017"
208:"03/11/2017"
Can someone help?
Thanks all for your help, I have managed to take some of the advice here and create the object and see it logging out:
var x = $('img[alt="MI_TAG"]').attr("src");
var split = x.split("&");
var arrayLength = split.length;
var arr = [];
var i = 0;
do {
arr.push(split[i].replace('=',':'));
arr.toString();
console.log(arr);
i += 1;
} while (i < arrayLength);
let mi = {};
arr.forEach(item=>{
let tempArr = item.split(':');
mi[tempArr[0]] = tempArr[1];
})
console.log(mi);
The issue I now seem to be facing is scope, I want my object to be globally referenceable, how do I do that?
From your array, use reduce - split on the = sign in your string, and create the object:
let newObject = arr.reduce((obj, item) => {
let parts = item.split("=");
obj[parts[0]] = parts[1];
return obj;
}, {});
Assuming you are using at least ECMAScript 5.1 you could use Array.prototype.forEach() to iterate over your array and produce the object.
let myArray = ["109=jsp.searchFlights.initial", "117=Flight Only Journey", "206=02/11/2017", "208=03/11/2017",
"212=ALL"];
let myObject = {};
myArray.forEach(item=>{
let tempArr = item.split('=');
myObject[tempArr[0]] = tempArr[1];
})
console.log(myObject);
Produces:
{
"109": "jsp.searchFlights.initial",
"117": "Flight Only Journey",
"206": "02/11/2017",
"208": "03/11/2017",
"212": "ALL"
}
Is it possible to stringify an object and then save it locally in a cookie, then retrieve it and parse it to revert it back to normal the next time the user logs on?
Tried to cram it all into once sentence. Here's an example of what I meant:
var theObject = {
oProp : 10,
oProp : true
};
var jString = JSON.stringify(theObject);
createCookie("object", jString);
var objectRetrieved = JSON.parse( readCookie("object") );
theObject = objectRetrieved;
If this is possible, what about storing each of the objects property/values individually?
Thanks in advance!
If you use jquery here is a cleaner approach to this-
Don't explicitly say JSON.Stringify.Instead of that you can set $.cookie.json = true;
Then store the object to cookie.
var myObj= { //what ever your properties }
$.cookie('myObj', myObj);
When reading back from cookie I would do
var myObj = $.cookie('myObj');
alert('Property name is ' + myObj.YourPropertyName);
Just as an alternative to cookie method, you can also use local storage like so:
var myObj = {"name":"n1","val":3,"bool":true};
localStorage.setItem('save', JSON.stringify(myObj));
var tmp = localStorage.getItem('save');
var round_trip = JSON.parse(tmp)
I imported json data into google scripts with:
var doc = Utilities.jsonParse(txt);
I can access most of the objects like such...
var date = doc.data1.dateTime;
var playerName = doc.data1.playerName;
var playerId = doc.data1.playerID;
var teamNumber = doc.data2.personal.team;
A bunch of objects I need to access have numbers as object names...
doc.data2.personal.team.87397394.otherdata
doc.data2.personal.team.87397395.otherdata
doc.data2.personal.team.87397396.otherdata
doc.data2.personal.team.87397397.otherdata
...but when I try to read the data with...
var teamId = doc.data2.personal.team.87397394;
... I get an error "Missing ; before statement."
I tried this...
var teamId = doc.data2.personal.team[87397394];
... and get "teamId undefined" in the log.
I also tied this with the same result...
var teamId = doc.data2.personal.team[+'6803761'];
I can read in the names as strings very easily with "For In", but can't get to the objects themselves. Every example I've found so far uses the brackets so I'm stumped what to try next.
Thank you!
Brian
UPDATE
I used this per your suggestions to get the object name into a variable and using the variable in brackets. No error but var test remains "undefined"...
for(var propertyName in doc.data2.personal.team) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
Logger.log (propertyNames);
var test = doc.data2.personal.team[propertyName];
}
The log shows the object names, as expected...
87397394
87397395
87397396
87397397
I'm thinking it's a bug in Google's implementation. Here is an example if anyone wants to verify it. test will return undefined...
function myFunction1() {
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = Utilities.jsonParse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
Logger.log (propertyName);
var test = doc.datablock_battle_result.vehicles[propertyName];
}
}
The problem seems to be in the Utitlies.jsonParse. The following works fine
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = JSON.parse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
var vehicle = doc.datablock_battle_result.vehicles[propertyName];
Logger.log('Vehicle id is ' + propertyName);
Logger.log('Vehicle value is ' + JSON.stringify(vehicle));
break;
}
var list = {};
list[19] = 'kapooya';
list[20] = 'apples';
delete list[19];
Does
list[19] == 'apples' or null?
var list = {};
list[19] = 'kapooya';
list[20] = 'apples';
delete list[19];
( var list[xx] would not work due to syntax error )
list[19] would be undefined.
Apart from the syntax error you get when using varbefore list[19] = 'kapooya', list[19] is undefined after the delete, not null.
Technically you are not creating a list but an object, or a map, or a hash, or a dictionary, however you wish to refer to it.
The correct syntax for working with lists, or in the case of javascript, Arrays, is var list= []; be aware that the delete operator doesn't work on array items.