adding properties to an object - javascript

I wrote this code and it`s simple , i have an empty object which will contain some other objects as properties , but the object stays empty and don`t add the needed properties ..
let buildProfileClientValidator = function(form , rules){
let elements = {};
function init(){
//Some code that works fine
addElement(elementName , elementType);
addElement(elementName , elementType);
//the elements object should now have some other objects as properties
//but it`s empty !!!!
console.log(elements);
}
function addElement(elementName , elementType){
//this condition works fine
if( !elementExist(elementName) ){
//console.log(elementName , elementType); also works fine -> the values of elementName , elementType are present
elements[elementName] = {
type : elementType,
value : '',
rules : (rules[elementName] == undefined) ? '' : rules[elementName].split('|')
};
}
}
}
so what i`m missing ?!

After examining your code, but not knowing how buildProfileClientValidator gets called (and specifically what the rules parameter is), I can trace the problem to this line:
(rules[elementName] === undefined) ? '' : rules[elementName].split('|')
I have modified your code (to make it testable) in the following fiddle (https://jsfiddle.net/hssbsL19/40/) and when I replace that line with a static value, the code works.

Related

How do I set a JavaScript object's value to null

I have created this JS object from an array.
var rv = {};
$( ".part-name:visible" ).each(function( index ) {
//rv[$(this).text()] = arrayPartsName[$(this).text()];
rv[$(this).text()] = arrayPartsName[$(this).text()];
console.log(rv);
})
4GN: "4GN"
4GNTS: "4GNTS"
042645-00: "042645-00"
503711-03: "503711-03"
573699-05: "573699-05"
I have to use this object with Materialize Autocomplete and I have to edit it. The correct object must be, for example, like this
4GN: null
4GNTS: null
042645-00: null
503711-03: null
573699-05: null
How can do this?
Picking up from my comment. You can just set it to null ;) JavaScript is quite a cool language... you can pretty much set any object's properties to anything you want, null, a specific value, or even a function... see some more on the topic
But to focus on your specific question:
Change this line
rv[$(this).text()] = arrayPartsName[$(this).text()];
to
rv[$(this).text()] = null;
Something to be aware of
If you have property or key values in the JSON object with a dash in the name, you have to wrap it in quotes ", otherwise it wont be seen as valid. Although this might not be as evident, or an issue in your example as your keys are being added via the following function $(this).text().
var fruit = {
"pear": null, // something null
"talk": function() { console.log('WOOHOO!'); } // function
}
var apple = "app-le";
fruit[apple.toString()] = 'with a dash';
fruit["bana-na"] = 'with a dash';
// below is not allowed, the values will be evaluated as
// properties that dont exist, and then your js will fail
// fruit[pe-ar] = 'with a dash';
fruit.talk();
console.log(fruit);

Changing the JSON key and keeping its index same

I want to change the key of JSON attribute and keep/persist its position/Index.
E.g.
{"Test1" : {
mytest1:34,
mytest2:56,
mytest6:58,
mytest5:89,
}
}
Now I want to change the key mytest6 to mytest4 and keep its position as it is.
Note: In my case I can't use Array.
Thanks.
jsonObj = {"Test1" : {
mytest1:34,
mytest2:56,
mytest6:58,
mytest5:89,
}
};
var old_key = "mytest6";
var new_key = "mytest4";
if (old_key !== new_key) {
Object.defineProperty(jsonObj.Test1, new_key,
Object.getOwnPropertyDescriptor(jsonObj.Test1, old_key));
delete jsonObj.Test1[old_key];
}
console.log(jsonObj);
This method ensures that the renamed property behaves identically to the original one.
Also, it seems to me that the possibility to wrap this into a function/method and put it into Object.prototype is irrelevant regarding your question.
Fiddle

Script debugger confirms intended conditional check between JSON key and string, however I am getting an undesired result?

I am looking to modify the output table I am getting from this handy Json-to-HTML-Table script I stumbled upon here on SO. There is a point (line 86) where json-to-table.js passes a JSON object and generates array keys to be used as table headers. Optionally, this array_key function can generate only one key for a specified search_value parameter passed. I however [attempted] to modify it so that ALL array keys that did NOT match the search_value would be returned. Here is the function after my changes:
function array_keys(input, search_value, argStrict)
{
var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = '', key = '';
if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
return input.keys(search_value, argStrict);
}
for (key in input)
{
if (input.hasOwnProperty(key))
{
include = false;
if (search)
{
if (strict && input[key] == search_value)
include = false;
else if (input[key] == search_value)
include = false;
else
include = true;
}
if (include)
tmp_arr[tmp_arr.length] = key;
}
}
return tmp_arr;
}
Now, the reason I did this is because I want my generated table to not include a specific column from my JSON object:
{
"examItemCategories": [
{
"catgoryName": "01-Normal processes",
"catgoryPath": "General Area\\01-Normal processes",
"numberOfItems": 2,
"percentage": "6.06"
}
]
}
Given that I can not modify the original JSON obj passed, I was determining whether or not to attempt to modify the table post creation (e.g. remove column), or during. After looking at the array_keys function, I felt I could easily invert the conditional checking for the search_value.
I now call array_keys(parsedJson[0], 'catgoryPath'); from json-to-table script. (Yes, catgoryPath is the correctly spelled name haha). Then I set a break point at the for loop within array_keys function to follow it through in Firebug.
First iteration: catgoryName is added to tmp_arr, 2nd iteration: catgoryPath is added to tmp_arr...and continues through 3rd and 4th iterations. I do not wantcatgoryPath added.
Looking at script debugger, on the 2nd iteration, whether or not catgoryPath gets added comes down to the conditional: else if (input[key] == search_value) line. The thing is, on the respective iteration both key and search_value variables equal "catgoryPath" according to Firebug. So therefore, include = false; should fire correct?
Any help is appreciated, apologies for the length and liberal usage of inline code.
Instead of using the array_keys function from the json-to-table script, if you are using JS > 1.8.5 you can use Object.keys(obj) to return an array of a given object's own enumerable properties.
The returned array of keys are then used as table headers under which the table populates with JSON data thanks to the script. Prior to the creation of table, I took my array of table headers and used array.splice(index, howMany) instead of delete (see here) to preserve my array index values.

Unique values in javascript hash

I need to push a hash into array only if it doesn't contain the hash that i want to add.
For example i have an array of hashes :
var someArray = [
{field_1 : "someValue_1", field_2 : "someValue_2"},
{field_1 : "someValue_3", field_2 : "someValue_4"},
{field_1 : "someValue_5", field_2 : "someValue_6"}
]
The value
{field_1 : "someValue_1", field_2 : "someValue_2"}
should not be pushed into array as it is already there, but the value
{field_1 : "someValue_7", field_2 : "someValue_8"}
should, as the array does't contain such value.
Is there any way to do it using jQuery?
Now i'm just using $.each loop and check if the array contains some hash. If it does i trigger a flag. But i don't like this solution.
create custom prototype to check the presence of object in the array. Please check the prototype design below.
Array.prototype.contains=function(x){
for(i in this){
if((x.field_1==this[i].field_1)&&(x.field_2==this[i].field_2))
return true;
}
return false;
}
Using above prototype, you can check if object present in an array.
var someArray = [
{field_1 : "someValue_1", field_2 : "someValue_2"},
{field_1 : "someValue_3", field_2 : "someValue_4"},
{field_1 : "someValue_5", field_2 : "someValue_6"}
];
var a1={field_1 : "someValue_1", field_2 : "someValue_2"};
var a2={field_1 : "someValue_7", field_2 : "someValue_8"};
if(!someArray.contains(a1)) someArray.push(obj); // it will NOT BE pushed
if(!someArray.contains(a2)) someArray.push(obj); // it will be pushed
Alternatively, you can augment Array or define your prototype as the following :
Array.prototype.add = function(element){
var itemExists = false;
for(var i=0;i<this.length;i++){
if(this[i]==element){
itemExists = true;
break;
}
}
if(itemExists==false)
return this.push(element);
}
So, using [].add(yourElement) will only add that element to your array if it doesn't already exist. Feel free to change the structure of the argument and if condition according to your needs.
I have faced this issue a lot of times, and what I always do is to write a function that returns true if the element is already in given set of elements.
function IsElementInSet(Element,Set)
{
var ElementIsInSet=false;
for(var i=0;i<Set.length;i++)
{
if(Set.field_1==Element.field_1&&Set.field_2==Element.field_2)
{
ElementIsInSet=true;
break;
}
}
return ElementIsInSet;
}
This is how I do the things. Create function that do some checks and give me true if the element is already there.
There are other possible solutions to optimise the search if you are working with big arrays and feel the things working slow, but I doubt you will.
EDIT: Also, about using parallel structure for saving current values - you can find it very tricky to have ordinary array (one dimension) in which only one value is saved - in your case it will be Element.field_1+Element.field_2 (concatenate the strings). Then you can write other function that check if there is given value in this array. I think the two solution are the same and it is question about style, not speed.

Javascript: Object function causing problems

I have tag trigger working by setInterval and it alerts when it find the tag in the document. the code did not have any problem until I've got the function into an object for arrangement,
Live examples:
here is an working example without object : http://jsfiddle.net/ae6Xc/4/
here is example with object (with the problem) : http://jsfiddle.net/ae6Xc/10/
here is the "original" working code without the object:
// looking for the special tag than save the
// element in varabile and than alert
(function(){
var win = window ,
doc = document ,
setInter = 'setInterval' ,
clearInter = 'clearInterval' ,
getByTagName = 'getElementsByTagName' ,
KW_pluslike = 'mysite:plugin' ,
zero = 0 ,
element;
// Set 'setInterval' function as trigger
// to target the Special tag.
var trigger = win[setInter](function(){
// Check if such tag exist , if not repeat. When the tag
// has founded , it set the root to the Element var.
if(doc[getByTagName](KW_pluslike)[zero]){
element = doc[getByTagName](KW_pluslike)[zero];
win[clearInter](trigger);
alert("Tag Captured");
}
} , 1000 /5 );
})();
so as i said , i wanted to arrange the things up a little so i took the Trigger function and the Element variable and replaced them into an object like this :
var pluslike = {
element : nul ,
trigger : win[setInter](function(){
if(doc[getByTagName](KW_pluslike)[zero]){
pluslike.element = doc[getByTagName](KW_pluslike)[zero];
win[clearInter](pluslike.trigger);
alert("Tag Captured");
}
} , 1000 /5 );
}
pluslike.trigger;
somehow for some reason it's not working , what causes the problem? i don't know. when it started? when i used the function in object.
thank you in advance.
A semicolon inside the object literal is causing your problem. Fixed code: http://jsfiddle.net/ae6Xc/11/Inside an object literal, properties should be separated by commas. Semicolons are not allowed
Comparison of your code, and the patched code:
trigger : win[setInter](... , 1000 /5 ); //<---Semicolon!!!#!#!#
trigger : win[setInter](... , 1000 /5 ) //<-- Patched, no semicolon

Categories

Resources