I'm using the JQuery Autocomplete plugin, with local data stored in a array:
data = [city1, city2, city3, city1]
Once the user selects the data element, for example city 1, I store it in user_input. I use the user input to read a hash that contains city, state zip, and name. The script displays each element of the hash on screen when the user hits enter. This also works great:
$(document).keypress(function(e) {
if(e.keyCode == 13) {
var user_input = $("input#example").val()
$.each(personinfo,function(key,value){
if(value['city']== user_input){
$('#city').empty().append(value['city']);
$('#state').empty().append(value['state']);
$('#zip').empty().append(value['zip']);
$('#name').empty().append(value['name']);
}
})
The problem arises when there are two identical keys. For instance, say a name "John Doe" and "Jane Doe", live in the same city: city1. Therefore city1 appears twice in the data array, as you see above.
data is defined in this method:
var data = new Array();
$(document).ready(function(){
$.each(personinfo,function(key,value){
myarray.push(value['city'])
});
});
How can I differentiate amongst city1 and city1 in the above array within the keypress function?
The personinfo map object:
{"address":"07288 Albertha Station","city":"Littelside","created_at":"2011-05-25T19:24:51Z","id":1,"name":"Jane Doe","state":"Missouri","updated_at":"2011-05-26T21:25:54Z","zip":"75475-9938"},{OBJECT 2}, {OBJECT 3}, ....
As some of the comments suggest, it's impossible to fix a problem with identical keys: the only way to fix it is to use non-identical keys :-)
I'd just combine city and state to make the key; seems like that should give you a unique keyset.
It's probably late now, but I just had to fix this problem in a similar plugin and the best way of doing it is to pass additional reference with the lookup data.
As in lookup = { data: ['name1', 'name2', 'name2', 'namex'], ref:[1,2,3,4] }
So that when user selects second 'name2' the plugin will return selected 'name2' and ref 3.
It depends on a plugin if it supports this functionality, but even if it doesn't you should be able to modify it slighlty.
Related
I want to update all the fields in a MongoDB document and I have a Javascript object that contains all these fields. I could easily type out each field to update but this seems like a lot of manual work and not reusable. I wanted to do something like below but this creates an object containing all the new field data within the document called newData.
I've tried JSON.stringify on the variable but the format isn't appropriate for update.
var newData = {
_id:ObjectId("53245234..."),
id: 88888,
firstData: "someData",
secondData: 787855,
thirdData: [ 45,17,12,234]
};
var collection = db.get('CollectionToUpdate');
//strip out dB id so as not to overwrite it, possibly not needed
if ("_id" in newData) {
delete newData["_id"];
}
//find the correct document based on program generated id and update
collection.update({id: newData.id}, {
newData
})
If you trust newData will not have any keys you don't intend (like update operators) this should work:
var collection = db.get('CollectionToUpdate');
collection.update({id: newData.id}, newData)
Note that this replaces the document. I assume that is what you meant by "update all the fields". update does not replace "_id".
Documentation for update
I'm trying to find the most efficient and generic solution for my single page app. There is 5 different tabs. Each tab is loading data in JSON object. Once user clicks on the tab JSON data is populated in the object with unique key. If user clicks on the Edit button I'm looping through JSON data and populating form fields. Here is my problem I have checkbox, radio, text and drop down menu fields on my form. Each data type requires different data type. My data in JSON object is not converted for checkbox or radio type input fields. I'm wondering what is the best way to approach this problem?
Here is example of my JSON data:
var jsonData = {
"frmTab1":{"st_fname":"mike","st_lname":"cook","st_iseligible":"yes"},
"frmTab2":{"sa_condition":"yes","sa_evaluation":"no"},
"frmTab3":{"se_respons":"yes","se_option":"3"},
... and so on
}
Here is my JQuery function that populates the form:
$('input[name="hmButton"]').on('click', function formSubmit(){
var btnVal = $(this).val();
if(btnVal == 'Edit'){
var jsonKey = $(this).attr('data-json'); //In data json is from id value
if($.isEmptyObject(jsonData[jsonKey])){
console.log('no data');
}else{
$.each(jsonData[jsonKey], function(index, element) {
//Here I need to check the input type and set checked if type is checkbox, or value if it's radio type, and same thing for drop down.
$('#frm' + index).val(element);
});
}
}
});
I was wondering if this could be done with another JSON object that will have key for each field with input type that is not equal text. If anyone can help please let me know. I'm trying to make this dynamic. This might be use in some other situation in my app. Thank you.
This...
var jsonData = {
'frmTab1': {
'st_fname': 'mike',
'st_lname': 'cook',
'st_iseligible': 'yes'
},
'frmTab2': {
'sa_condition': 'yes',
'sa_evaluation': 'no'
},
'frmTab3': {
'se_respons': 'yes',
'se_option': '3'
}
}
... is a JavaScript Object. JSON is a text-based data-interchange format, and although it's written in JavaScript Object Notation (hence JSON) try to avoid confusing JavaScript Objects with JSON data. Now that's out of the way... :)
Although JSON keys have to be defined between quotes ("...") as long as the keys in a JavaScript Object obey the usual syntax requirements the quotes for keys can be dispensed with...
var jsonData = {
frmTab1: {
st_fname: 'mike',
st_lname: 'cook',
st_iseligible: 'yes'
},
frmTab2: {
sa_condition: 'yes',
sa_evaluation: 'no'
},
frmTab3: {
se_respons: 'yes',
se_option: '3'
}
};
Your suggestion of referencing another Object which acts as an intermediary between the function which populates your page and the information in the jsonData variable is workable - perhaps something like this...
var dataMap = {
waypoint_1: jsonData.frmTab1,
waypoint_2: jsonData.frmTab2,
waypoint_3: jsonData.frmTab3
/* ... etc ... */
};
What I have called 'waypoint_n' here would reflect the properties/strings you're expecting to retrieve from your page element attributes - so that Something like...
var dKey = /* attribute value or property (String) */
var data = dataMap[ dKey ];
...would then place the required information from the jsonData Object in the data variable.
However, as you already have this information in an Object (jsonData) why not simply amend its keys to reflect the attribute values you're expecting?
You may find these links useful:
Eloquent JavaScript: The Secret Life of Objects
Eloquent JavaScript: Data Structures: Objects and Arrays
MDN: Working with JSON data
I wasnt exactly sure what i should name this question so feel free to edit the title.
I am running an angular application and using node.js combinded with express and sequlize (for my ORM)
Now as many of you may know when your working with an ORM you want to collect Objects inside of another Object for instance a user object might have a country object inside of it as shown below:
user = {id: 222, username: 'Marc', name: 'Marc Ras', country: {id: 1, code: 'DK', name: 'Denmark'}}
Now this is great. binding all of these objects together makes it alot easier to work with in the frontend.
However the other way around is rather annoying.
Lets for the purpose of demonstration take the above object. but lets add a property an array of items
user.items = [{id: 1 , name:'item1'}, {id: 2, name: 'item2'}]
Now if i wish to add this object to my database i would send the combined object to my express route:
var user = {
id: 222,
username: 'Marc',
name: 'Marc Ras',
country: {id: 1, code:'DK', name: 'Denmark'}
items: [
{id: 1, name: 'item1'},
{id: 2, name: 'item2'}
]
}
And now things get abit messy
Say for instance you have the following table:
user_has_items
Each record in this has an id, user_id, item_id
Now in order to make sure that the objects inside user.items match the table you will now have to make code gymnastic by making loops and editing the above object.
Like as such:
user.items.forEach(function (x) {
x.item_id = x.id;
x.id = null; // To make sure the database does not set the id (since this is auto inc)
x.user_id = user.id;
})
Note the above is of course an example it gets more complicated the bigger your object is!
This process leads to messy code (atleast in my opinion) and since this is not the first time i encounter this problem i was wondering if any of you had any solutions as to what you might do to make this process easier?
I have been looking at lodash to see if they had some way of doing this but sadly i could not find anything that made this easy
I'm new to JS. In an application I am extending I have to different kinds of views. I one, I want to see full product names, and in the other only their abbreviations.
I wouldn't like to hard-code them but to write them in a file. What's a good way to accomplish that? I thought about creating an json/xml/text file which would look something like this
'product name 1' : 'abbr1'
'product name 2' : 'abbr2'
[...]
but I need the result to work in both directions, like either passing an abbreviation and getting the full name or the other way round. I can use javascript and jquery.
Edit: I want not to hard-code the data because the products are subject to change, so I wouldn't really like them to be in the source code. I think stuff like this which can frequently change should be stored outside the source code so it can be changed easier.
You could create the array of products in a JSON file. Something like:
[{name: "Product 1", abbr: "pr1"}, {name: "Product 2", abbr: "pr2}...]
Then you could use jQuery's getJSON method as such:
$.getJSON( "ajax/test.json", function( json ) {
// do something with the json
});
However, that being said. I don't see much benefit from this approach, as the JSON would be hard-coded too.
Edit: Actually I do see a benefit. This at least decouples your data source with the retrieval of data.
Put your your products data in a global array:
<script>
function product(name, code) {
this.name = name;
this.code = code;
};
var productArray = [ new product("Apple", "a"), new product("Orange", "o") ];
// user array
for (var i = 0; i < productArray.length; ++i)
if (productArray[i].name == "Apple")
console.log(productArray[i].code);
</script>
I'm looking for a way to take a bunch of JSON objects and store them in a data structure that allows both fast lookup and also fast manipulation which might change the position in the structure for a particular object.
An example object:
{
name: 'Bill',
dob: '2014-05-17T15:31:00Z'
}
Given a sort by name ascending and dob descending, how would you go about storing the objects so that if I have a new object to insert, I know very quickly where in the data structure to place it so that the object's position is sorted against the other objects?
In terms of lookup, I need to be able to say, "Give me the object at index 12" and it pulls it quickly.
I can modify the objects to include data that would be helpful such as storing current index position etc in a property e.g. {_indexData: {someNumber: 23, someNeighbour: Object}} although I would prefer not to.
I have looked at b-trees and think this is likely to be the answer but was unsure how to implement using multiple sort arguments (name: ascending, dob: descending) unless I implemented two trees?
Does anyone have a good way to solve this?
First thing you need to do is store all the objects in an array. That'll be your best bet in terms of lookup considering you want "Give me the object at index 12", you can easily access that object like data[11]
Now coming towards storing and sorting them, consider you have the following array of those objects:
var data = [{
name: 'Bill',
dob: '2014-05-17T15:31:00Z'
},
{
name: 'John',
dob: '2013-06-17T15:31:00Z'
},
{
name: 'Alex',
dob: '2010-06-17T15:31:00Z'
}];
The following simple function (taken from here) will help you in sorting them based on their properties:
function sortResults(prop, asc) {
data = data.sort(function(a, b) {
if (asc) return (a[prop] > b[prop]);
else return (b[prop] > a[prop]);
});
}
First parameter is the property name on which you want to sort e.g. 'name' and second one is a boolean of ascending sort, if false, it will sort descendingly.
Next step, you need to call this function and give the desired values:
sortResults('name', true);
and Wola! Your array is now sorted ascendingly w.r.t names. Now you can access the objects like data[11], just like you wished to access them and they are sorted as well.
You can play around with the example HERE. If i missed anything or couldn't understand your problem properly, feel free to explain and i'll tweak my solution.
EDIT: Going through your question again, i think i missed that dynamically adding objects bit. With my solution, you'll have to call the sortResults function everytime you add an object which might get expensive.