cookie in React JS (save/load) - reactjs

I am new to using cookies in React JS and I have a question regarding my code below.
console.log(this.state.datasets);
cookie.save('datasets', this.state.datasets, { path: '/' , 'maxAge': 100000});
var myArray = cookie.load('datasets')
console.log(myArray);
this.state.datasets is an array full of elements and went I initially print the array to the console, I am able to see the data.
However when I try printing out myArray I get an empty array. Any idea what could be going wrong?

You can save only strings as cookies. To save an array you'll have to somehow convert it into a string. If you have an array of objects you can store it by converting it into string by JSON.stringify.
For example
let colors = [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
}]
let x = JSON.stringify(colors)
The value x will be a string which you can save to cookies.
And to retrieve it you can convert it back to an array of objects by using JSON.parse.
Something like
var myArray = cookie.load('datasets')
let obj = JSON.parse(myArray)
obj will be the original object

Related

How can would I translate this array of JS objects into an array of Swift tuples?

I'm trying to structure my data in Swift and I'm having a hard time initializing an the empty array of nested tuples and arrays.
I'm new to Swift, very familiar with JS.
Here is how my data would be structured in JS:
let data = [] // Loop will push objects into this variable
// This is the object that would be pushed into data from within a loop - for range in ranges
ranges.forEach(range => {
data.push({
[range]: {
'minDate': Date(),
'minDateText': '',
'tags': [{
'name': '',
'color': '',
'total': ''
}]
}
});
});
I've tried a few different things in swift, but I'm just not getting it. Seems like you have to have an exact representation of the array before its actually holding any data. I need to initialize it without any data.
The latest thing I've tried is this:
var data:[(String:(String:Date, String:String, String:[(String:String, String:String, String:String)]))] = []
// Get error "Cannot create a single-element tuple with an element label"
You should stop thinking how to code in JS and start reading about how to code in Swift. You can start with Apple Swift book, it covers almost everything you need to get started. So what you really need is to structure your data:
struct Object {
let minDate: Date
let minDateText: String
let tags: [Tag]
}
struct Tag {
let name: String
let color: String
let total: String
}
Then you can create a dictionary or an array with it:
var dictionary: [String: Object] = [:]
var objects: [Object] = []

Removing empty array values on multidimensional array

I want to remove arrays cctype, cctypologycode, and amount when they are empty from array. best way to do it ?
{
"ccInput": [
{
"designSummaryId": 6,
"CCType": "A",
"CCTypologyCode": "A",
"Amount": "1"
},
{
"designSummaryId": 7,
"CCType": "",
"CCTypologyCode": "",
"Amount": ""
},
]
}
ccInput[1] should be removed from the array
If you want to remove some objects from your array, use Array.prototytpe.filter().
You can do it in an immutable way by copying each property of your object using the spread operator and then filter the ccInput property:
const obj = {ccInput:[{designSummaryId:6,CCType:"A",CCTypologyCode:"A",Amount:"1"},{designSummaryId:7,CCType:"",CCTypologyCode:"",Amount:""}]};
const result = { ...obj, ccInput: obj.ccInput.filter(x => x.CCType && x.CCTypologyCode) };
console.log(result);
Or if you want to modify your object in place, simply reassign the ccInput property:
const obj = {ccInput:[{designSummaryId:6,CCType:"A",CCTypologyCode:"A",Amount:"1"},{designSummaryId:7,CCType:"",CCTypologyCode:"",Amount:""}]};
obj.ccInput = obj.ccInput.filter(x => x.CCType && x.CCTypologyCode);
console.log(obj);
I don't know much about TypeScript, but I do know you can set the array to []. However, for those of you looking to get rid of only part of an array but not all of it, the simplest way to do so that I know of is to just set each value to 0 for numbers, '' for characters, "" for Strings, etc.

How can I dynamically add values to my typescript array?

I'm trying to dynamically populate my pieChartColors array, so that in the end my array will look something like this:
public pieChartColors:Array<Color> = [
{
backgroundColor: '#141C48'
},
{
backgroundColor: '#FF0000'
},
{
backgroundColor: '#EFEFEF'
},
...
]
I'm starting with a blank array and have tried a few different ways to get the values added, but none of them are working (my color values are stored without the hash symbol):
public pieChartColors: Array<Color> = [];
public buildPieChart() {
...
for (let pie of pieData) {
// none of these work
this.pieChartColors.push(backgroundColor: '#'+pie.backgroundColor);
this.pieChartColors.backgroundColor.push('#'+pie.backgroundColor);
this.pieChartColors['backgroundColor'].push('#'+pie.backgroundColor);
}
...
}
BTW, pieData is an object I'm looping through from the database with the backgroundColor values. If I console.log the pie.backgroundColor, the value is available.
Just do it like in JavaScript:
this.pieChartColors.push({backgroundColor: '#'+pie.backgroundColor});

Add subelement to JSON array

I have the following code where I design the format of a JSON-array dynamically from variables ==>
var Title = '"text_title"'
var Topic2 = '"text_topic2"'
var jsonData = [ ];
createWantedJSON("title", data[i].topic, jsonData)
function createWantedJSON(title, Topic2, arr) {
arr.push({
"Topic": title,
[Topic2] : {
"Topic3": [{
"Subitem1": "Text1",
"Subitem2": "Text2",
"Subitem3": "Text3"
}]
}
}
This goes fine for the key and value which are not nested. But I don't know how to make it dynamic for the content of Topic3. I tried making a variable with the following content =>
'"Subitem1": "Text1", "Subitem2": "Text2", "Subitem3": "Text3"' but then of course it sees the content as one string and not as elements of the nested Topic3 array. I guess this isn't that hard but I can't seem to fix it.

AngularJS: Trying to clean up an API Feed by processing $http response is not working

I have an API Feed of global variables to be used throughout an application. The raw feed looks like this:
[
{
id: "1",
var: "g_crop_year",
val: "2015"
},
{
id: "2",
var: "g_season",
val: "F"
}
]
To me, that is awkward to work with throughout an application and I would prefer it look like this:
[
{ g_crop_year: "2015" },
{ g_season: "F" }
]
I tried this:
$http.get('/globals')
.success(function(globals){
var simpleGlobals = [];
for(var g=0; g<globals.length;g++){
var glo = {
globals[g].var: globals[g].val
};
simpleGlobals.push(glo);
}
$scope.globals = simpleGlobals;
});
My thoughts were to loop through the returned data, create the structure I want and push to a new array which I assign to $scope. But I am wrong. I get a blank page and an unexpected token in the globals[g].var: globals[g].val line.
This will not work as you expect:
var glo = {
globals[g].var: globals[g].val
};
They key of the glo object is attempting be the literal text globals[g].var; change that, instead, to:
var glo = {};
glo[globals[g].var] = globals[g].val;
As a side note, you may want to assign to $rootScope or a Service to make these globals available to all of your controllers.
This is not the right approach to create your designated approach.
var glo = {
globals[g].var: globals[g].val
};
The string globals[g].var is actually being considered as the key rather than interpreting it as a value.
You should instead create a blank object first and then use the array annotation to assign a particular value to the key.
var glo = {};
glo[globals[g].var] = globals[g].val;

Resources