function get_event_ids_from_dom()
{
var event_ids = {};
$.each(
$("td.ms-cal-defaultbgcolor a"),
function(index,value){
var str = new String(value);
var id = str.substring(str.indexOf('=')+1,str.length);
if(typeof(event_ids[id]) == "undefined")
{
event_ids[id] = this;
}
else
{
**event_ids.id.push(this);**
}
}
)
return event_ids;
}
In above javascript event_ids is a hashtable. I am trying to assign values to this hashtable.
A hashtable can be added with multiple values using "hashtable.key.push(value)". I am trying to do this using event_ids.id.push(this); in the above code.
I have declared "id" as a variable in the code. The problem is, I am not able to dereference variable "id" to its value.
Is this possible in jquery/javascript?
Example use of hashtable:
event_ids = {};
event_ids["1"]= 'John';
event_ids.1.push('Julie');
The above example would add john and julie to hash table.
Try this instead:
function get_event_ids_from_dom() {
var event_ids = {};
$.each(
$("td.ms-cal-defaultbgcolor a"),
function(index,value){
var str = value.toString();
var id = str.substring((str.indexOf('=') + 1), str.length);
if(typeof(event_ids[id]) == "undefined") {
event_ids[id] = [];
}
event_ids[id].push(this);
});
return event_ids;
}
Please, note that while object["id"] is the same as object.id, object[id] is not.
Nicola almost had it:
if(typeof(event_ids[id]) == "undefined") {
event_ids[id] = [];
}
event_ids[id].push(this);
Also please read the comment I left for your question.
In my opinion event_ids is an object (there are no hastables in javascript, just either indexed arrays or objects).
What you are tring to do is using push (an array method) on something that is not an array so i think you must change something:
you could try:
if(typeof(event_ids[id]) == "undefined")
{
event_ids[id] = [];// the property id of object event_ids is an array
event_ids[id].push(this);
}
else
{
event_ids[id].push(this);
}
It should work
Related
Say I have object:
function obj()
{
this.prop1;
this.prop2;
this.prop3;
}
and an array of obj's
objects = [new obj(),new obj(),new obj()];
I want to easily iterate through each using jquery where the class name is equivalent to the property of the object.
var itemsIWantToBind = ["prop1","prop2","prop3"];
for(j=0;j<itemsIWantToBind.length;j++)
{
$("."+itemsIWantToBind[j]).unbind().blur(function(){
var id = $(this).siblings(".objID").html();
if(id >= 0)
{
objects[id].itemsIWantToBind[j] = $(this).text());
}
});
}
My issue is I want to be able use a variable variable to iterate through the items for this
objects[id].itemsIWantToBind[j] = $(this).text());
^^^^^^^^^^^^^^^^^
the indicated part does not correctly bind the value of the array item as it is trying to bind the property name of it instead.
In php it would be the same as:
foreach($itemsIwantToBind as $item)
{
$objects[$id]->$item = "Something";
}
Is there a simple way to do this in JavaScript?
Use brackets notation:
var o = new obj();
o.prop1 = "I'm the value";
var s = "prop1";
console.log(o[s]); // "I'm the value"
I think this is how this relates to your code:
["prop1","prop2","prop3"].forEach(function(prop) { // **A**
$("."+prop).unbind().blur(function(){
var id = $(this).siblings(".objID").html();
if(id >= 0)
{
objects[id][prop] = $(this).text()); // **B**
}
});
});
(B) is the place where we actually use the name, but note the (A) change to so that we get a value that won't change. You can't just use
// Wrong unless we also change the loop
objects[id][itemsIWantToBind[j]] = $(this).text());
because j will be be beyond the end of the array when the event occurs.
forEach is an ES5 feature that can readily be shimmed for old browsers. Or you can use jQuery's $.each instead:
$.each(["prop1","prop2","prop3"], function(i, prop) { // **A**
$("."+prop).unbind().blur(function(){
var id = $(this).siblings(".objID").html();
if(id >= 0)
{
objects[id][prop] = $(this).text()); // **B**
}
});
});
Below javascript code for adding object to a javascript array. I want to add an object to array when it does not exist, if it already exists object.rValue!= new object.rValue then change old rValue=new rValue, otherwise same rVale. Also save it on array.
The problem is the object populate dynamically.
var arr = [];
$(document).ready(function() {
$(".rating").click(function() {
var idx = $(this).closest('td').index();
var userskill = {
tech : $(this).closest('td').siblings('td.tech').text(),
skill : $('#listTable thead th').eq(idx).text(),
rValue : $(this).val()
}
validate(userskill);
});
});
function validate(userskill) {
}
Try this
arr.forEach(function(elem){
if(elem.rValue==newObj.rValue)
elem.rValue = newObj.rValue;
})
I need a way to add an object into another object. Normally this is quite simple with just
obj[property] = {'name': bob, 'height': tall}
however the object in question is nested so the following would be required:
obj[prop1][prop2] = {'name': bob, 'height': tall}
The clincher though, is that the nesting is variable. That is that I don't know how deeply each new object will be nested before runtime.
Basically I will be generating a string that represents an object path like
"object.secondObj.thirdObj.fourthObj"
and then I need to set data inside the fourth object, but I can't use the bracket [] method because I don't know how many brackets are required beforehand. Is there a way to do this?
I am using jQuery as well, if that's necessary.
Sure, you can either use recursion, or simple iteration. I like recursion better. The following examples are meant to be proof-of-concept, and probably shouldn't be used in production.
var setDeepValue = function(obj, path, value) {
if (path.indexOf('.') === -1) {
obj[path] = value;
return;
}
var dotIndex = path.indexOf('.');
obj = obj[path.substr(0, dotIndex)];
return setDeepValue(obj, path.substr(dotIndex + 1), value);
};
But recursion isn't necessary, because in JavaScript you can just change references.
var objPath = 'secondObj.thirdobj.fourthObj';
var valueToAdd = 'woot';
var topLevelObj = {};
var attributes = objPath.split('.');
var curObj = topLevelObj;
for (var i = 0; i < attributes.length; i++) {
var attr = attributes[i];
if (typeof curObj[attr] === 'undefined') {
curObj[attr] = {};
}
curObj = curObj[attr];
if (i === (attributes.length - 1)) {
// We're at the end - set the value!
curObj['awesomeAttribute'] = valueToAdd;
}
}
Instead of generating a string...
var o="object";
//code
o+=".secondObj";
//code
o+=".thirdObj";
//code
o+=".fourthObj";
...you could do
var o=object;
//code
o=o.secondObj;
//code
o=o.thirdObj;
//code
o=o.fourthObj;
Then you can add data like this:
o.myprop='myvalue';
And object will be updated with the changes.
See it here: http://jsfiddle.net/rFuyG/
I'm using a hash table and I'm trying to check for object existence. However I haven't been successful in figuring out how to do this. Could someone help guide me with this. Thanks.
current code.
When clientId equals field id and has item id return true, else add to saved_tokens.
var saved_tokens = {};
if ($.inArray(item.id, saved_tokens) == -1) {
saved_tokens.push[clientId] = item.id;
}
Don't use jQuery for that. Use pure JavaScript:
if (!saved_tokens.hasOwnProperty(clientId)) { // If clientId is not in the hash
saved_tokens[clientId] = item.id;
}
.push is an array method. A {} creates an object. Since this object is not an array, it doesn't have any array methods.
I personally use 'typeof'.
var saved_tokens = {};
if (typeof(saved_tokens[clientId]) == 'undefined') {
saved_tokens[clientId] = item.id;
}
Given the following HTML form:
<form id="myform">
Company: <input type="text" name="Company" value="ACME, INC."/>
First Name: <input type="text" name="Contact.FirstName" value="Daffy"/>
Last Name: <input type="text" name="Contact.LastName" value="Duck"/>
</form>
What is the best way serialize this form in javascript to a JSON object in the format:
{
Company:"ACME, INC.",
Contact:{FirstName:"Daffy", LastName:"Duck"}
}
Also note that there might be more than 1 "." sign in the field name.
I think that what you'd do is this: for each input, first split the name at the separators (the '.' characters). Now, you have an array of names. You can then iterate through that array, making sure that your target "assembly" object (and sub-objects) have containers every time you come across a new name segment. When the array has 1 element in it, you simply add the value.
$.fn.extractObject = function() {
var accum = {};
function add(accum, namev, value) {
if (namev.length == 1)
accum[namev[0]] = value;
else {
if (accum[namev[0]] == null)
accum[namev[0]] = {};
add(accum[namev[0]], namev.slice(1), value);
}
};
this.find('input, textarea, select').each(function() {
add(accum, $(this).attr('name').split('.'), $(this).val());
});
return accum;
});
// ...
var object = $('#myform').extractObject();
I just sort-of made that up so there might be a bug or two; I can't remember whether all the browsers have "slice" but I think they do.
(edit: I forgot the all-important call to split())
You can loop through the form fields by name, use String#split to split the names on dot, and build up your resulting structure. Concept code:
function serializeDeep(form) {
var rv, obj, elements, element, index, names, nameIndex, value;
rv = {};
elements = form.elements;
for (index = 0; index < elements.length; ++index) {
element = elements[index];
name = element.name;
if (name) {
value = $(element).val();
names = name.split(".");
obj = rv;
for (nameIndex = 0; nameIndex < names.length; ++nameIndex) {
name = names[nameIndex];
if (nameIndex == names.length - 1) {
obj[name] = value;
}
else {
obj = obj[name] = obj[name] || {};
}
}
}
}
return rv;
}
Note that that doesn't allow for fields with repeated names (which should create arrays), nor does it elegantly handle a situation where you use the names "foo" and "foo.bar". But it should get you started.
I have managed it this way:
$('#Myform').attr('onsubmit', 'test()');
function test() {
var obj = {};
obj.title =$('#title').prop('value');
console.log('title: '+obj.title);
obj.website =$('#website').prop('value');
console.log('website: '+obj.website);
obj.tags =$('#tags').prop('value').split(',');
console.log('tags: '+obj.tags);
do_something(JSON.stringify(obj));
}
Of course this can be done if you know what the names are, and I am in fact generating the table itself using Formation plug-in.
I created an example for this question by using plain js, please check developer tool console to see the data object!
jsfiddle example
var data = {};
var array = 'person.name.first'.split('.');
var value = 'myFirstName';
generateObj(data, array, value);
console.log(data);
function generateObj(obj, arr, val) {
if (arr.length === 1) {
obj[arr[0]] = val
return;
}
var restArr = arr.splice(1);
if (!obj[arr[0]]) {
obj[arr[0]] = {};
}
generateObj(obj[arr[0]], restArr, val);
}
solution:
transform each name string to array.
iterate through each array.
recursively call a method which create an obj and set this obj as the value of the property and pass this obj to the next recursion.
Create an object of that shape then use a JSON encoder to write it out.