$.cookie("matrizTela", null);
objCookie = {};
for(var i = 1; i<vList.length;i++){
for(var z=0;z<vList[i].length;z++){
listaY = vList[i][z].childNodes[0].attributes;
listaX = vList[i][z].style;
$.each(listaY,function(key,val){
objCookie[val.nodeName] = val.nodeValue;
});
$.each(listaX,function(key,val){
metodo = "listaX."+val;
propValue = eval(metodo);
objCookie[val] = propValue;
});
console.log(objCookie);
//Need now add objCookie in my cookie in list form!
}
};
OBS: vList is matrix of lists of the DOM Object
How can I dynamically add my objCookie in list form on my cookie?
Example:
$.cookie("matrizTela", ["objCookie", "objCookie","objCookie"]);
A cookie can store only String values.
The best you can do to store an array of objects is to serialize the array and store it as a string.
$.cookie("matrizTela", JSON.stringify(yourObjectArray));
For reading it back, you can do:
yourObjectArray = JSON.parse($.cookie("matrizTela"));
Related
I add an array localstorage. works fine. I can also retrieve it . how can I.update where ID is something without adding a new array.
example ..
how can I go update surname and age where ID = sam without creating new array
var objItem = {};
if (localstorage.getItem("records") == null) {
objArr = [];
} else {
objArr = JSON.parse(localstorage.getItem("records"));
}
var ID = "sam";
var surname = "edward";
var age = "two";
objItem.ID = ID;
objItem.surname = surname;
objItem.age = age;
objArr.push(objItem);
localstorage.setItem("records", JSON.stringify(objArr));
localStorage is just a key-value store. To update, you just save to the same key. That is, you retrieve your array, parse, update, stringify then save to the same key.
To find the item on the array, you can use array.filter and create an array containing only the values that match the ID. Update the values inside that array and save the original array.
let names = [...names...];
let matches = names.filter(person => person.ID === ID);
matches.forEach(person => person.surname = surname);
let toSave = JSON.stringify(names);
// save to localstorage
I'm parsing a fairly large JSON file and doing some key:value pairs within an object. Issue I'm having is if I find a key I need to actually add another object to it INSTEAD of writing over it.
Example:
var collection = {};
angular.forEach(things, function(thing) {
collection[thing.Id] = thing.stuff;
//thing.stuff is an object
});
Came to a conclusion after some of the comments I've received in the first post:
var collection = {};
angular.forEach(things, function(thing) {
if(collection[thing.Id]){
//Key Exists push into array
collection[thing.Id].push(thing.stuff);
}else{
//Key doesn't exist create array for object
collection[thing.Id] = [thing.stuff];
}
});
In Modern way: maybe someone will come in handy
var collection = {};
angular.forEach(things, function(thing) {
if(!collection[thing.Id]){
collection[thing.Id] = [];
}
collection[thing.Id] = [...collection[thing.Id], thing.stuff];
// or ----------------------------------------------------
// add item at start
// collection[thing.Id] = [thing.stuff, ...collection[thing.Id]];
// or ---------------------------------------------
// if you doesn't want to change referrance every time
// collection[thing.Id].push(thing.stuff);
});
I'm trying to get all of the domain's cookies and store the name and the value into two separate arrays. Let's say I got the cookies with document.cookie and parsed it into an array:
["cookie0=value0","cookie1=value1"]
How could I extract the name and the values and turn it into two separate arrays? Should be like this:
var cookie_names = ["cookie0","cookie1"]
var cookie_values = ["value0","value1"]
I've tried to extract them with .split, but have no clue how to implement them.
Can you try out this function
function myFunction () {
var cookie_names = [];
var cookie_values = [];
var cookies = ["cookie0=value0","cookie1=value1"];
var count = 0;
for(var i in cookies){
cookie_names[count] = cookies[i].split("=")[0];
cookie_values[count] = cookies[i].split("=")[1];
count++;
}
console.log(cookie_names);
console.log(cookie_values);
}
But you have to make sure that cookies array should be in the proper format so that it can be splitted by =. In my opinion, it would be much easier of you can make the cookies array an JS Object.
eg: var cookies = {"cookie0" : "value0", "cookie1" : "value1"}
In which case you can change the for loop into this
for(var i in cookies){
cookie_names[count] = i;
cookie_values[count] = cookies[i];
count++;
}
I would like to overwrite a certain allOrders[i] with data, similar to how I create a new one. For some reason I can't figure out what to search on.
I have an array of objects allOrders.
I have an object BusinessCard. I take the form fields, serialize() them, clean up the data with a regex, then push the them into an array.
allOrders.push(new BusinessCard(currentOrder.quantity, currentOrder.FullName, currentOrder.Title, currentOrder.CellNumber, currentOrder.OfficeNumber, currentOrder.FaxNumber, currentOrder.EmailAddress, currentOrder.Address, currentOrder.website, currentOrder.price));
I've tried searching for overwriting existing object properties in an array and the likes and haven't figured out what to do here.
My best guess was allOrders[i].push -- but it seems to me that I have to write a new function to replace each property in the object.
Right now I am using(because using serialize() on the form inputs doesn't help me at all:
allOrders[i].quantity = $('#bcQuantity').val();
allOrders[i].fullname = $('#fullName').val();
allOrders[i].title = $('#Title').val();
allOrders[i].cell = $('#CellNumber').val();
allOrders[i].office = $('#OfficeNumber').val();
allOrders[i].fax = $('#FaxNumber').val();
allOrders[i].email = $('#EmailAddress').val();
allOrders[i].address = $('#Address').val();
allOrders[i].website = $('#website').val();
allOrders[i].price = $('#bcCostBeforeCart').text();
There has to be a smarter way to do this. Thank you.
EDIT:
function getFormData(formId) {
var currentForm = '#' + formId;
var currentPrice = $('#bcCostBeforeCart').text();
var currentFormData = $(currentForm).serialize();
var currentFormDataFinal = currentFormData + '&price=' + currentPrice;
return JSON.parse('{"' + decodeURI(currentFormDataFinal.replace(/\+/g, " ").replace(/&/g, "\",\"").replace(/=/g, "\":\"")) + '"}');
}
MEANING i could be using
currentOrder = getFormData('businessCardForm');
then
allOrders[i] = currentOrder;
Seems odd that you would be updating all items with the selector's you're using, but I would wrap up getting the updated order information then, you can run thru a loop.
Depending on your output, as long as it's outputing the respective properties and values of an order object you could just do:
for(int i =0; i < allOrders.length; i++){
var currentFormId = '' // update this for each iteration.
allOrders[i] = getFormData(currentFormId);
}
allOrders[i] = getUpdatedOrder();
function getUpdatedOrder() {
var order = {};
order.quantity = $('#bcQuantity').val();
order.fullname = $('#fullName').val();
order.title = $('#Title').val();
order.cell = $('#CellNumber').val();
order.office = $('#OfficeNumber').val();
order.fax = $('#FaxNumber').val();
order.email = $('#EmailAddress').val();
order.address = $('#Address').val();
order.website = $('#website').val();
order.price = $('#bcCostBeforeCart').text();
return order;
}
i am trying to pass non numeric index values through JSON but am not getting the data.
var ConditionArray = new Array();
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
When i alert the Data Variable it has the Values 1,2 and 3 but module and table are not included. How can this be added so that the whole string is passed.
EDIT : And what if i have some multidimensional elements also included like
ConditionArray[0] = new Array();
ConditionArray[0] = "11";
JSON structure only recognizes numeric properties of an Array. Anything else is ignored.
You need an Object structure if you want to mix them.
var ConditionArray = new Object();
This would be an better approach:
var values = {
array : ["1", "2", "3"],
module : "Test",
table : "tab_test"
};
var data = JSON.stringify(values);
Since javascript array accepts numeric index only. If you want non numeric index,use Object instead.
var ConditionArray = {};
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
Here is the working DEMO : http://jsfiddle.net/cUhha/
According to the algorithm for JSON.stringfy (step 4b), only the (numeric) indices of arrays are stringified.
This is because Array does not contain your elements.
When you do this:
ConditionArray['module'] = "Test";
You actually add a property to the ConditionArray, not elements. While JSON.stringify converts to string only elements of the ConditionArray. For example:
var arr = new Array;
arr['str'] = 'string';
console.log(arr.length) //outputs 0
You need to use an Object instead of Array
If you change the first line to
var ConditionArray = new Object();
you will achieve the desired outcome.
If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API.
In the function you can now decide what to do with value of key is of a specific type.
this is the way how I solved this problem
Where tblItemsTypeform is array and arrange is de index of the array
:
let itemsData = [];
for(var i = 0; i <= this.tblItemsTypeform.length -1;i++){
let itemsForms = {
arrange: i,
values: this.tblItemsTypeform[i]
}
itemsData.push(itemsForms)
}
And finally use this in a variable to send to api:
var data = JSON.stringify(itemsData)