I format a string (I can format the string in any way)
e.g
id1:234,id2:4566,id3:3000
then encrypt it and pass via query string
?qs=djdjdjfjf57577574h33h3h3hh3h3
then decrypt it on node
id1:234,id2:4566,id3:3000
which is the best method to format the string and then turn it into an array in node
arr[id1] = "234";
arr[id2] = "4566";
arr[id3] = "3000";
2 Answers 2
I think you would like to use hashmap (object) instead of array:
var obj = {}
then try:
"id1:234,id2:4566,id3:3000".split(",").forEach(function(e){
var record = e.split(":");
obj[record[0]] = record[1];
})
which give you:
{id1: "234", id2: "4566", id3: "3000"}
4 Comments
each function. You can use forEach, but this is not supported for <IE8."each" since on Chrome there is :)each function as far as I can tellFirstly, what you have as your object model is more of a hash like object or simply a JavaScript object with keys and values, so the best way to do that is simply using JSON.parse.
So if you can do it as you said: I can format the string in any way, you better first change your formatting to have something like:
'{"id1":234,"id2":4566,"id3":3000}'
instead of :
id1:234,id2:4566,id3:3000
you can do it using JSON.stringify on the client side JavaScript using a JavaScript object without you needing to deal with string formatting:
//on the client side
var myObj = {};
myObj.id1 = 234;
myObj.id2 = 4566;
myObj.id3 = 3000;
var objStr = JSON.stringify(myObj);
let's say you encrypt your string using a function named encrypt:
var encryptedStr = encrypt(objStr);
//so now you should use encodeURI to be able to put it in the queryString
var queryStringParam = encodeURI(encryptedStr);
now you put the queryStringParam in the queryString.
Then on the node.js side, all you should do is parsing it as a JSON object. The other important point that you probably have considered doing it is using decodeURI. For the last step, let's say you are using e function named decrypt:
//the server-side code
var decryptedStr = decrypt(decodeURI(yourQueryString));
var obj = JSON.parse(decryptedStr);
Now obj is exactly what you want.
id1,id2andid3supposed to be in your example? They are not variables, but string literals right?