storing javascript array with special characters inside a cookie - javascript

i searched around stackoverflow and found out that cookie only can store string not array.
i have an array like this:
var myvar = {
'comment' : '123',
'blog' : 'blog',
'test' : '321
}
Then i use this jquery plugin to manage the cookies:
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
I use the below code to store the cookie named 'setting':
$.cookie('setting', myvar , { expires: 1, path: '/' });
However how do i convert that array into a string , i know i can use .join , but what if my array values for example comment , is a special character like Chinese characters etc.
and how can i access the cookie again and get the string out and convert it again into an array?

To store an object in a cookie:
var myvar = {
'comment' : '123',
'blog' : 'blog',
'test' : '321'
};
var serialized = JSON.stringify(myvar);
$.cookie('setting', serialized, { expires: 1, path: '/' });
To retrieve an object from a cookie :
JSON.parse($.cookie("setting"));
See this answer for examples of JSON.stringify and JSON.parse.

Related

getting information from a javascript json object

I imagine this has been posted before but I wasn't able to find a data object specifically like this one. I'm struggling to understand how extract information from this data object in javascript. It's a parsed URL.
data = URL {
href: 'http://localhost:8080/test.txt?cat=Mouse',
origin: 'http://localhost:8080',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:8080',
hostname: 'localhost',
port: '8080',
pathname: '/test.txt',
search: '?cat=Mouse',
searchParams: URLSearchParams { 'cat' => 'Mouse' },
hash: ''
}
I can retrieve the URLsearchParams
data.searchParams, which returns { 'cat' => 'Mouse' }
What is this data structure called: { 'cat' => 'Mouse' }. I'm confused by the =>
And how do I retrieve the two objects 'cat' and 'Mouse' separately inside this data structure?
For example, retrieving then setting a variable equal to the first item, 'cat' and another variable equal to 'Mouse'
Thank you
What is this data structure called: { 'cat' => 'Mouse' }.
That isn't a data structure. It's a visual representation of the data in the URLSearchParams object.
Look at the API documentation to see how to access it (e.g. data.searchParams.entries())
There is absolutely nothing JSON related to that.

convert a string containing JavaScript object to a JSON string with PHP

This is the javascript Object (just a small part of it):
dataToReturn = {
"dimensionsDisplayType" : [
"dropdown","swatch",
],
"pwEnabledDimensionMap" : {
"size_name": true,
"color_name": true
},
"isPWBadgeEnabled" : true,
"isImmersiveExperience" : false,
"isTabletWeb" : false
}
So in PHP it will look like:
<?php
$jsObjStr = '{
"dimensionsDisplayType" : [
"dropdown","swatch",
],
"pwEnabledDimensionMap" : {
"size_name": true,
"color_name": true
},
"isPWBadgeEnabled" : true,
"isImmersiveExperience" : false,
"isTabletWeb" : false
}';
But if we would like to parse it with json parse we cant In PHP since its not a clean JSON format because of
"dimensionsDisplayType" : [
"dropdown","swatch",
]
The keys containing object like "dimensionsDisplayType" can be unpredictable so cleaning with regex for example wont help much.
The one that works is
JSON.stringify(dataToReturn)
But in my case I can not run client side code sot it must be converted into the correct JSON format in server side with PHP. I was searching a lot online but I got not any satisfying function or library.
How can this be solved ?
You could try cleaning the string with this regex, this will look for a comma followed by optional whitespace and a close ] and replace this with the content minus the comma...
$jsObjStr = preg_replace("/,(\s*?])/", "$1", $jsObjStr);

Upsert data with a dynamic field name

I just try to do something simple with Mongo but it doesn't work:
I want to upsert datas in an object like: module.xxx.yyy then I tried many things like :
UsersRights.upsert({
condoId: condoId,
userId: manager._id,
}, {
condoId: condoId,
userId: manager._id,
module: {
[defaultRight.xxx] : {
[defaultRight.yyy] : defaultRight.default
}
}
});
but when I want to add a new xxx or a new yyy, it will erase and replace the entire module object and not only add a new key.
I also tried this :
UsersRights.upsert({
condoId: condoId,
userId: manager._id,
}, {
condoId: condoId,
userId: manager._id,
["module." + defaultRight.module + "." + defaultRight.right] : defaultRight.default,
});
but the server show me an error like: MinimongoError: Key module.xxx.yyy must not contain '.'
You need to use the following form:
YourCollection.upsert({
_id: id, (can be other selectors as well)
}, {
$set: setter
});
Setter is an object you create before and should have the following form:
const setter = {};
setter[`${#1Level}.${#2Level}`] = data;
Where #1Level & #2Level are vars naming the fields you want to modify or to add.

How to find the element based on its name in mongodb

I need to find the object whose name is "abc" from category collection in mongodb. Here is the my code
[{
_id: 728e38e7,
name: 'abc,def,ghi,klm,nmo',
place: "mys"
},
{
_id: 2788,
name: 'djhd',
place: "bang"
}]
try that
var query = { name: new RegExp('^' + abc) };
collection.find(query).toArray(function(err, items))
Using the mongo shell you can use find().
db.collection.find({"name" : /abc/}).
From this post : How to query MongoDB with "like"?
Below is the simplest method of using regex to find element based on name in mongodb :
db.collection.find({name:{$regex:"ABC",$options:"$i"}})
Here $i is used to make the search case insensitive.

Access the property of a object inside a object

I need to pull the value of property "title"
KV = {
clientPath: '/0000000000/client',
serverPath: '',
application: '/00000000/client/application/player.js',
properties: '/000000000/client/custom-config/AppProperties.js',
pollingEnabled: false,
customerConfig: {},
presentationTypeConfig: {},
kuluConfig: {},
kulu: {
"guid" : "XXXXXXX",
"title" : "XXXXX",
"createdInApp" : false,
"allowFeedback" : true,
"publisher" : {
"id" : 000000001,
"username" : "XXXXXXX",
"name" : "XXXXXXXX"
},
I tried looping but I just get returned undefined.
I have no access to the code to change it.
Have you tried this?
KV.kulu.title
first of all: the json you have posted is invalid. publisher-property has only an opening curly bracket.
second: here's a working fiddle, with valid json and just the code kv.kulu.title which does exactly what you are (literally) asking for:
http://jsfiddle.net/k75cxdkh/1/
edit: I'm just guessing here, but re-reading your question and json code, it seems you try to loop over an array of objects to get a nested object by it's value dynamically. When trying this, do it e.g. like this (using underscorejs):
var arr = _.filter(KV, function(obj) {
return _.some(obj.kulu, {id: ID_TO_FIND});
});
if not, nevermind. It's just a bit weird you are asking for a such common task.
quick and easy: KV.kulu.title no loop required!

Categories