Data storage in jquery - javascript

I want to store objects in jquery. The objects are 'events' each event has a date, title and some text. They need to be stored like and array (maybe thats what they will be a multi-dimensional array) so I can iterate through them with a counter.
Edit,
I like the stores var as a way to group the info but how do I add multiple items and how do I index them?
var dates = new Array('12th Dec', '14th Jan', '6th May');
var event_title = new Array('My Birthday', 'Going to Beach', 'Holiday');
var event_text = new Array('One Year Older', 'Remember the suntan lotion', 'on the plane to spain');
I need to return by index alert(dates[2], event_title[2], event_text[2]);

you can try:
var store = {};
store = {
dates : dates,
titles: titles,
infotxt: infotxt
};
Then access:
store.dates or store.title or so..

You probably don't want to store separate related info in arrays as you're doing, and then attempt to access those groups by index.
JavaScript has a perfect, native object that allows you to group similar properties. Just use an object literal:
var events = [];
events.push({
data: someData,
title: someTitle,
text: someText
});
Now you have what's referred to oftentimes as a "collection".
You could take it a step further and make each event a "class":
function MyAwesomeEvent(data, title, text) {
this.data = data;
this.title = title;
this.text = text;
}
events.push(new MyAwesomeEvent(someData, someTitle, someText));
That approach is potentially heavy-handed depending on what your specific use-case is, but it's another option.

Related

javascript - JSON file use a value only if key exists

I'm retrieving an OSM Json from an overpass call, to obtain a list of features that I have to save on a database. Since the data are very different from one another (for example, some of them do have a a tag called "addr:city", and some of them not), I would like to check if a key exists, and only in that case save the corresponding value. I've found only this question but it's not my case, since I do not know a priori which keys one element will have and which not, and since I'm working with a great load of data, I really can't check the elements one by one and of course I can't write an IF for each case.
Is there a way to solve this? I was thinking something about "if key has null value, ignore it", while looping over the elements, but I don't know if something like that exists
EDIT:
This is my query:
https://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(node[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696);way[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696););out%20center;
and this is the code I'm using to save the data on firebase:
results.elements.forEach(e=>{
var ref = firebase.database().ref('/point_of_interest/');
var key = firebase.database().ref().child('point_of_interest').push().key;
var updates = {};
var data = {
città: e.tags["addr:city"],
tipologia: e.tags["amenity"],
indirizzo: e.tags["addr:street"],
nome: e.tags["name"],
lat: e.lat,
lon: e.lon
}
updates['/point_of_interest/'+key] = data;
firebase.database().ref().update(updates);
})
"results" is the response in json format
You could use something like that:
var attrs = ["addr:city", "amenity", "addr:street", "name"];
var labels = ["città", "tipologia", "indirizzo", "nome"]
var data = { };
attrs.forEach((a, i) => {
if (e.tags[a]) { data[labels[i]] = e.tags[a]; }
});
You could even make this more dynamic, if you can query the attribute names and labels from somewhere.

Saving Dynamic Data in Objects?

I have a simple time entry form, see here: https://codepen.io/dikuw/pen/rmpozm
I want to store the time data dynamically as the user adds, modifies, and deletes rows and am thinking objects is the best approach.
My question is what is the best practice? Should I create a constructor, e.g.
function TimesheetRecord(id, TSDate, TSStaffId, Hours, Comments, TSTaskId, Billable) {
this.id = id;
this.TSDate = TSDate;
this.TSStaffId = TSStaffId;
this.Hours = Hours;
this.Comments = Comments;
this.TSTaskId = TSTaskId;
this.Billable = Billable;
}
and then dynamically create a new object every time the user adds a row? If I do that, how will I know how many objects there are?
Here you can create an Array to store your all TimesheetRecords and push a new dynamic object when you create a new one.
// When app starts (dataFromDB is data fetched from db if any)
const TimesheetRecords = dataFromDB || []
// create a new record(mainly in a function)
const TimesheetRecord = {
id: id,
TSDate: TSDate,
TSStaffId: TSStaffId,
Hours: Hours,
Comments: Comments,
TSTaskId: TSTaskId,
Billable: Billable
}
// store to db (ajax) and then push to array
TimesheetRecords.push(TimesheetRecord)
// Check how many records are there
const count = TimesheetRecords.length
This is common pattern for storing simple objects without any behaviors(methods) in JavaScript.

converting each array value ias object in javascript not working

This is my array:
var country = ["US(+1)","IND(+91)"];
And i want to convert my array in this below format:
country = [
{
title: "US(+1)",
},
{
title: "IND(+91)",
}
]
word title should be same for each array value.
with this code am trying to get my expected result as above
var obj = country.reduce(function(o, val) { o['title'][] = val; return o; }, {});
But my output is comes like this as below: only last index is taking place
{"title":"IND(+91)"} this is wrong output which i dont want
You may be able to do it with reduce but it's much easier to use map:
var country = ["US(+1)","IND(+91)"];
var obj = country.map(function(c){return {title:c}});
console.log("country:", country);
console.log("obj:", obj);
map is for when you want to turn an array of things into another array of things, and reduce is when you want to turn an array of things into just a single thing.
var country = ["US(+1)","IND(+91)"];
I would use a more descriptive word since it is a list of countries.
var countries = ["US(+1)","IND(+91)"];
But to answer your question, to manipulate an array into a new array, I like to use the array.map method:
var objects = countries.map(function(country){ return { title: country } });
Here is the documentation for map:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?v=control

Javascript matrix array issue

I'm creating a very simplified version of a drag and drop shopping cart with jqueryui.
My issue is regarding adding data(id, name, price) to an array.
I tried several methodes of adding the data (also an array) to the main container(array). But I keep getting this error: Uncaught TypeError: undefined is not a function
var data = [];
function addproduct(id,name,price){
//var d = [id,name,price];
data[id]["name"] = name;
data[id]["price"] = price;
data[id]["count"] = data[id]["count"]+1;
console.log(data);
}
the addproduct() function can be called by pressing a button
It is not entirely clear to me what type of data structure you want to end up with after you've added a number of items to the cart. So, this answer is a guess based on what it looks like you're trying to do in your question, but if you show a Javascript literal for what you want the actual structure to look like after there are several items in the cart, we can be sure we make the best recommendation.
You have to initialize a javascript object or array before you can use it. The usual way to do that is to check if it exists and if it does not, then initialize it before assigning to it. And, since you're keeping a count, you also will want to initialize the count.
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id]["name"] = name;
data[id]["price"] = price;
++data[id]["count"];
console.log(data);
}
And FYI, arrays are used for numeric indexes. If you're using property names like "name" and "price" to access properties, you should use an object instead of an array.
And, I would suggest that you use the dot syntax for known property strings:
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id].name = name;
data[id].price = price;
++data[id].count;
console.log(data);
}
It looks like what you want is an array of objects, although I would need a more detailed description of your problem to be clear.
var data = []
function addproduct(id, name, price)
{
data.push({'id': id, 'name':name, 'price': price, 'count': ++count});
console.log(data);
}

How can I parse a JSON object containing a colon

I have an object which comes back as part of a return data from a REST server. It is part of an item object.
(I don't have control over the REST server so I can't change the data received):
{
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
What I want to end up with is some control over this, so that I can display the results when a product is selected in my app. It will appear in a modal. I am using Marionette/Backbone/Underscore/JQuery etc. but this is more of a JavaScript question.
I have tried multiple ways of getting at the data with no success. I would like to be able to have the options in a nested array, but I'd be open to other suggestions...
Basically this kind of structure
var Color=('Red', 'Green', 'Blue', 'Orange')
var Size('Small', 'Medium', 'Large')
The Object structure is fine, just need to be able to translate it to an array and take out the 'Option' keyword
Important to mention that I have no idea what the different options might be when I receive them - the bit after Options: might be any form of variation, color, size, flavour etc.
Loop through the parsed JSON and create new keys on a new object. That way you don't have to create the var names yourself; it's automatically done for you, albeit as keys in a new object.
var obj = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
function processObj() {
var newObj = {};
for (var k in obj) {
var key = k.split(':')[1].toLowerCase();
var values = obj[k].split(',');
newObj[key] = values;
}
return newObj;
}
var processedObj = processObj(obj);
for (var k in processedObj) {
console.log(k, processedObj[k])
// color ["Red", "Green", "Blue", "Orange"], size ["Small", "Medium", "Large"]
}
Edit: OP I've updated the code here and in the jsfiddle to show you how to loop over the new object to get the keys/values.
Fiddle.
var json = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var color = json['Option:Color'].split(',');
var size = json['Option:Size'].split(',');
Try this to do get a solution without hardcoding all the option names into your code:
var x = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var clean = {};
$.each(x, function(key, val){ //iterate over the options you have in your initial object
var optname = key.replace('Option:', ''); //remove the option marker
clean[optname] = val.split(","); //add an array to your object named like your option, splitted by comma
});
clean will contain the option arrays you want to create
EDIT: Okay, how you get the names of your object properties like "color", which are now the keys in your new object? Thats the same like before, basically:
$.each(clean, function(key, val){
//key is the name of your option here
//val is the array of properties for your option here
console.log(key, val);
});
Of course we stick to jQuery again. ;)

Categories