Please forgive me in advance as I'm sure this is a noob question (I honestly searched google for an hour before I cam here);
Long Story:
Okay, so I'm creating an application that lists vehicles stored in a database. I have a JavaScript class called Car that is instantiated for each car listing. The class contains default values for everything (make, model, year, color, price, etc) and has a function to use a jQuery ajax request to have my php return the actual values for the car. I pass it with JSON and have a consistent naming convention, so my xhr object in my success function is basically a copy of the car object, only with the correct values. I'm trying to find a simple way to give the xhr object's properties to the car object without manually specifying all 30 options (I know it's doable, but I'm sure there must be a better method, and i'm always up to learn)
Short Story:
How can I use object-x's properties to overwrite object-y's when they have the exact same list of defined properties and both already exist?
Thank you very much in advance!
Well you would simply
$.extend( car, json );
Where car object is the target and json is the object where the correct values are
Docs http://api.jquery.com/jQuery.extend/
Jsfiddle demo http://jsfiddle.net/qApyZ/
Related
I would like to come straight to the point and show you my sample data, which is around the average of 180.000 lines from a .csv file, so a lot of lines. I am reading in the .csv with papaparse. Then I am saving the data as array of objects, which looks like this:
I just used this picture as you can also see all the properties my objects have or should have. The data is from Media Transperency Data, which is open source and shows the payments between institiutions.
The array of objects is saved by using the localforage technology, which is basically an IndexedDB or WebSQL with localstorage like API. So I save the data never on a sever! Only in the client!
The Question:
So my question is now, the user can add the sourceHash and/or targetHash attributes in a client interface. So for example assume the user loaded the "Energie Steiermark Kunden GmbH" object and now adds the sourceHash -- "company" to it. So basically a tag. This is already reflected in the client and shown, however I need to get this also in the localforage and therefore rewrite the initial array of objects. So I would need to search for every object in my huge 180.000 lines array that has the name "Energie Steiermark Kunden GmbH", as there can be multiple and set the property sourceHash to "company". Then save it again in the localforage.
The first question would be how to do this most efficient? I can get the data out of localforage by using the following method and set it respectively.
Get:
localforage.getItem('data').then((value) => {
...
});
Set:
localforage.setItem('data', dataObject);
However, the question is how do I do this most efficiently? I mean if the sourceNode only starts with "E" for example we don't need to search all sourceNode's. The same goes of course for the targetNode.
Thank you in advance!
UPDATE:
Thanks for the answeres already! And how would you do it the most efficient way in Javascript? I mean is it possible to do it in few lines. If we assume I have for example the current sourceHash "company" and want to assign it to every node starting with "Energie Steiermark Kunden GmbH" that appear across all timeNode's. It could be 20151, 20152, 20153, 20154 and so on...
Localforage is only a localStorage/sessionStorage-like wrapper over the actual storage engine, and so it only offers you the key-value capabilities of localStorage. In short, there's no more efficient way to do this for arbitrary queries.
This sounds more like a case for IndexedDB, as you can define search indexes over the data, for instance for sourceNodes, and do more efficient queries that way.
I am currently in the process of writing a GUI which fundamentally allows users to edit/populate/delete a number of settings files, where the settings are stored in JSON, using AJAX.
I have limited experience with JavaScript (I have little experience with anything beyond MATLAB to be frank), however I find myself restructuring my settings structure because of the semantics of working with an object containing more objects, rather than an array of objects. In C# I would do this using a KeyValuePair, however the JSON structure prevents me from doing what I'd really like to do here, and I was wondering whether there was an accepted convention for do this in JavaScript which I should adopt now, rather than making these changes and finding that I cause more issues than I solve.
The sample data structure, which has similar requirements to many of my structures, accepts any number of years, and within these any number of events, and within these a set number of values.
Here is the previous structure:
{"2013":
{
"someEventName":
{
"data1":"foo",
"data2":"bar",
...},
...},
...}
Here is my ideal structure, where the year/event name operates as a key of type string for a value of type Array:
["2013":
[
"someEventName":
{
"data1":"foo",
"data2":"bar",
...},
...],
...]
As far as I am aware, this would be invalid JSON notation, so here is my proposed structure:
[{"Key":"2013",
"Value":
[{"Key":"someEventName",
"Value":
{
"data1":"foo",
"data2":"bar",
...}
},
...]
},
...]
My proposed "test" for whether something should be an object containing objects or an array of objects is "does my sub-structure take a fixed, known number of objects?" If yes, design as object containing objects; if no, design as array of objects.
I am required to filter through this structure frequently to find data/values, and I don't envisage ever exploiting the index functionality that using an array brings, however pushing and removing data from an array is much more flexible than to an object and it feels like using an object containing objects deviates from the class model of OOP; on the other hand, the methods for finding my data by "Key" all seem simpler if it is an object containing objects, and I don't envisage myself using Prototype methods on these objects anyway so who cares about breaking OOP.
Response 1
In the previous structure to add a year, for example, the code would be OBJ["2014"]={}; in the new structure it would be OBJ.push({"Key":"2014", "Value":{}}); both of these solutions are similarly lacking in their complexity.
Deleting is similarly trivial in both cases.
However, if I want to manipulate the value of an event, say, using a function, if I pass a pointer to that object to the function and try to superceed the whole object in the reference, it won't work: I am forced to copy the original event (using jQuery or worse) and reinsert it at the parent level. With a "Value" attribute, I can overwrite the whole value element however I like, provided I pass the entire {"Key":"", "Value":""} object to the function. It's an awful lot cleaner in this situation for me to use the array of objects method.
I am also basing this change to arrays on the wealth of other responses on stackoverflow which encourage the use of them instead of objects.
If all you're going to do is iterate over your objects, then an array of objects makes more sense. If these are settings and people are going to need to look up a specific one then the original object notation is better. the original allows people write code like
var foo = settings['2013'][someEventName].data1
whereas getting that data out of the array of objects would requires iterating through them to find the one with the key: 2013 which depending on the length of the list will cause performance issues.
Pushing new data to the object is as simple as
settings['2014'] = {...}
and deleting data from an object is also simple
delete settings['2014']
My Google Chrome extension uses JSON.parse(oldJSONstring) to create an object with configuration information. The "oldJSONstring" was saved from previous sessions on Chrome's localStorage.
As I sometimes add new features, after I create the new object, I manually validate that all configuration entries exist, if not, I'll set them with default values. This is done, in case it's he firs time a user loads the extension after it updated.
I was trying to think of a more automatic way of doing this, like using a JSON Schmea, but I really don't know where to start, and my first round of google searches didn't produce anything I could use.
Another approach I thought was to iterate on all my Default settings -also stored on a JSON object- and then confirming they exist on the new object... but I just realized I don't know how to iterate a JSON object for all its attributes :)
The end goal of this is that I'd like to forget about validating for new attributes, every time I create a new feature and I publish a new version... does it make any sense? does it make me lazy? :D
Thanks!
Keep the default object handy and use jQuery $.extend to merge the 2 objects.
var defaults={ color:'blue', size:'Large'}
var chromeObj= /* code to grab from storage*/
/* update chromeObj with all key/value pairs in defaults */
/* regardless if they already exist or not*/
$.extend( chromeObj, defaults}
/* code to put chromeObj back to storage*/
Refrence: http://api.jquery.com/jQuery.extend/
There is no such thing as a "JSON object,"* but it's quite easy to loop over a Javascript object's properties: How do I loop through or enumerate a JavaScript object?
* JSON is just a string format, and it's a subset of Javascript object notation
To be honest, I'm not quite sure where to start with this question.
I'll describe the situation: I am in the process of making a level editor for an HTML5 game. The level editor is already functional - now I would like to save/load levels created with this editor.
Since this is all being done in Javascript (the level editor as well as the game), I was thinking of having the save simply convert the level to a JSON and the load, well... un-jsonify it.
The problem is - the level contains several types of objects (several different types of entities, several types of animation objects, etc...) Right now, every time I want to add an object to the game I have to write an unjsonify method specifically for that object and then modify the level object's unjsonify method so it can handle unjsonifying the newly defined type of object.
I can't simply use JSON.parse because that just returns an object with the same keys and values as the original had, but it is not actually an object of that class/prototype. My question is, then, is there a correct way to do this that does not require having to continuously modify the code every time I want to add a new type of object to the game?
I would create serialise/deserialise methods on each of your objects to put their state into JSON objects and recover it from them. Compound objects would recursively serialise/deserialise their children. To give an example:
function Player {
this.weapon = new Weapon();
}
Player.prototype.serialise = function () {
return {'type': 'Player', weapon: this.weapon.serialise()};
}
Player.deserialise = function(json_object) {
var player = new Player();
player.weapon = Weapon.deserialise(json.weapon);
return player;
}
Obviously in real code you would have checks to make sure you were getting the types of objects that you expect. Arrays and simple hash objects could be simply copied during serialisation/deserialisation though their children will often need to be recursed over.
Salesforce allows you to extend Object definitions by using Record Types. Is there a quick and easy way to allow users to transition groups of Objects from one Record Type to another? In my case, I will be keeping track of students as they progress through the undergraduate student life cycle from applicant to alumnus. It makes sense to me to keep track of the different phases of the student life cycle as Record Types so that I can create custom interfaces/viewing permissions/business logic for each phase. I was hoping to be able to create a custom button or link to do this as per this example from Salesforce:
Salesforce: Getting Started With Buttons and Links.
However I have had no luck querying the RecordType object using the Ajax toolkit to find out which RecordTypeId I will need to update the Object to. (I am rather new to JavaScript so it may simply be my inexperience that's getting in the way. I would be happy to post code samples of what I've tried so far if anyone asks.)
On the IdeaExchange someone mentioned that you can just include the RecordType field in the object's custom layout page (IdeaExchange: Provide a Means of Changing Record Types), but this does not seem like a reasonable solution for managing hundreds of students.
Using a workflow or a trigger does not seem like a reasonable solution either because those apparently require you to update a record or create a new one. Students should be able to transition at any time, independently of updates or new additions.
SO likes it when you mention other things that your issue could pertain to, but I think those areas are pretty self-explanatory here; this issue is relevant any time you might like to programatically transition between different record types.
What you want is probably not the RecordType object itself, but rather the RecordTypeId field on your object you are using to track students which looks up to that RecordType object. For example, to find the record type of a given student, the SOQL would look like:
SELECT RecordTypeId FROM Student__c WHERE Id = {some id}
and then if you wanted to update the record, you could change the value of the RecordTypeId like this:
var student = new sforce.SObject("Student__c");
student.Id = '{some id}';
student.RecordTypeId = '{new record type id}';
result = sforce.connection.update([student]);
To find the eligible RecordTypeIds for a given object type, you can either query the RecordType object and filter on the SObjectType column, or just call describeSObject(Student__c) and inspect the RecordTypeInfos node in the result.