js check if obj is available [duplicate] - javascript

This question already has answers here:
How to check if object property exists with a variable holding the property name?
(11 answers)
Closed 7 years ago.
So, I have following js :
var NAMES = {
'185' : {
'FIRST' : 'first',
'MIDDLE' : 'middle',
'LAST' : 'last'
}
};
for (var j = 0; j < (id.length); j++) {
var uDATA_ID = id[j]; //string
var uDATA_OBJ = JSON.parse(uDATA_ID); //converted to object
if (uDATA_ID == NAMES.uDATA_OBJ){
alert("Somethings happening");
}
}
So, I get a string of ids from php. I need to check if this number is available in the object variable.
However, I am having a hard time making it work.
Could someone help me out?
Thanks

To use a variable to access an object field, use the [field] syntax instead of the .field syntax:
var data = NAMES[uDATA_ID]
If that field is missing, it will return undefined (which you can then check for)
if (data) { // assumes you don't want `false` or `0`.

Related

for-loop not modifying a global variable? [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 6 years ago.
I wrote a for-loop that for some reason refuses to modify a global variable. Instead, it seems to create a local variable that it modifies temporarily. A condensed version of my code is as follows.
var clubsArray = [obj, obj, obj];
//each obj contains a property of "goalsFor" which holds an integer
var madridTotalGoals = 0;
var barcaTotalGoals = 0;
function findTotalGoals(clubsArray, totalGoals) {
for(var i = 0; i < clubsArray.length; i++) {
totalGoals += clubsArray[i].goalsFor;
}
}
findTotalGoals(clubsArray, barcaTotalGoals);
// this loops properly and does the math, but it never changes the value of barcaTotalGoals
In the full code there are numerous arrays that hold "club" objects; each contain a property key "goalsFor", which hold an integer as a value. There are also numerous "totalGoals" variables (two are specified here) that have been declared globally.
Does anyone know why the global variable (e.g. barcaTotalGoals) is not being modified when passed through this function? When I console log each step of this loop, the math is taking place but the result is not being stored. I apologize if this has been asked before but I've searched thoroughly.
The variable you are trying to pass, is passed by value and not reference. So it wont affect the original variable
You can assign the value once the for loop is finished
function findTotalGoals(clubsArray, totalGoals) {
for(var i = 0; i < clubsArray.length; i++) {
totalGoals += clubsArray[i].goalsFor;
}
barcaTotalGoals = totalGoals;
}
You are passing by value instead of by reference...
Instead, you could try like this:
clubsArray = [obj, obj, obj];
var totalGoals = {
madrid: 0,
barca: 0
}
function goalsByCountry(clubsArray, totalGoalsClub) {
for(var i = 0; i < clubsArray.length; i++) {
totalGoals[totalGoalsClub] += clubsArray[i].goalsFor;
}
}
goalsByTeam(clubsArray, 'barca');

Going through a object with a variable [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 6 years ago.
I guess I didnt really know how to ask this question for me to find an answer.
So I have three variables that are going to make this function do what it has to
function gatherDataForGeographic(ele) {
var $this = $(ele)
var $main_title = $this.find('.options-title'),
$option = $this.find('.option');
var arr = []
var reportAreas = reportManager.getReportAreasObject();
$option.each(function () {
var $this = $(this)
var $checkbox = $this.find('.checkbox');
var type = $this.data('type'),
index = $this.data('index');
if ($checkbox.hasClass('checkbox--checked')) {
console.log(reportAreas.type)
} else {
return true;
}
})
return arr;
}
//this will return an object that I need to index
var reportAreas = reportManager.getReportAreasObject();
//this will get the a key that i need from the object
var type = $this.data('type');
//this will give me the index I need to grab
var index = $this.data('index');
So what I am trying to do is go through the object based on the type(or key) from the option selected by a user
The problem...
It is looking for reportArea.type[index] and is not recognizing it as a variable and I keep getting undefined because .type does not exist.
Is there a way for it to see that type is a variable and not a key?
You can use dynamic properties in JS using the bracket syntax, not the dot syntax:
reportAreas[type]
That will resolve to reportAreas['whateverString'] and is equivalent to reportAreas.whateverString- reportAreas.type however, is a literal check for type property.
reportArea[type][index]
JavaScript objects are just key-value pairs and the dot syntax is just syntactic sugar for the array notation.
object['a']
and
object.a
Are the same thing, basically.

Jquery object assign to variable return undefined [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 7 years ago.
Working SO code below:
var property_object_parse = jQuery.parseJSON('{"p1":{"TextElement":[{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_company name","text":"Company name","font":"Plantagenet Cherokee","size":"9","h":"0.16","w":"1.15","y":"0.3","x":"0.53","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"company name","caption":"Company name","textType":"Company name","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"left","sortorder":"0","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_first name","text":"First name","font":"Plantagenet Cherokee","size":"7","h":"0.1","w":"1.14","y":"0.44","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"first name","caption":"First name","textType":"First name","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"1","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_last name","text":"Last Name","font":"Plantagenet Cherokee","size":"6","h":"0.11","w":"1.16","y":"0.56","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"last name","caption":"Last Name","textType":"Last Name","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"2","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_email","text":"Email","font":"Plantagenet Cherokee","size":"6","h":"0.1","w":"1.14","y":"0.69","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"email","caption":"Email","textType":"Email","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"3","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_phone","text":"Phone","font":"Plantagenet Cherokee","size":"6","h":"0.11","w":"1.14","y":"0.81","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"phone","caption":"Phone","textType":"Phone","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"4","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#1_street","text":"street","font":"Plantagenet Cherokee","size":"9","h":"0.17","w":"1.16","y":"0.95","x":"2.3","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"street","caption":"street","textType":"street","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"center","align":"right","sortorder":"5","inputformat":false,"format":false,"clippath":false,"inputrequired":false}]},"p2":{"ImageElement":[{"type":"image","text":"Sample.png","blockName":"Back Logo","id":"#2_Back Logo","lock":"false","rotation":"0","h":"0.68","w":"0.69","y":"0.59","x":"0.41","valign":"bottom","halign":"left","clippath":false}],"TextElement":[{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#2_Company Name","text":"Company Name","font":"Plantagenet Cherokee","size":"9","h":"0.16","w":"1.16","y":"1.3","x":"0.24","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"Company Name","caption":"Company Name","textType":"Company Name","bold":"false","colorspace":"DevicaeRGB","colorcode":"rgb(1.00,0.00,0.00)","color":"16711680","hex_color":"","valign":"bottom","align":"center","sortorder":"0","inputformat":false,"format":false,"clippath":false,"inputrequired":false},{"yscale":"100","xscale":"100","shadow":"false","rotation":"","id":"#2_Tagline","text":"Sample Tagline","font":"Helvetica","size":"12","h":"0.18","w":"0.73","y":"1.52","x":"0.25","lock":"false","customize":"false","Alpha":"100","underline":"false","italic":"","blockName":"Tagline","caption":"Sample Tagline","textType":"Sample Tagline","bold":"false","colorspace":"DeviceRGB","colorcode":"rgb(1.00,1.00,1.00)","color":"16777215","hex_color":"","valign":"top","align":"left","sortorder":"1","inputformat":false,"format":false,"clippath":false,"inputrequired":false}]}}');
var selected_element = 'p1.TextElement[0].size';
console.log(property_object_parse.selected_element);
I am getting undefined when I try to get the value using variable. Is this correct way to access it?
See my jsfiddle here
property_object_parse is a real JavaScript object, so you can just use the member access syntax to access the value you are interested in directly:
console.log(property_object_parse.p1.TextElement[0].size);
Note that you cannot use a dynamic property path string like 'p1.TextElement[0].size', you would have to compile that in a way. For example, you could instead have an array of properties you are trying to access:
var selected_element = ['p1', 'TextElement', '0', 'size'];
var obj = property_object_parse;
for (var i = 0; i < selected_element.length; i++) {
obj = obj[selected_element[i]];
}
console.log(obj);
That has the same result as accessing it all directly as above with property_object_parse.p1.TextElement[0].size.

How to Find Out if a Property in an Object Exists [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 7 years ago.
Does anyone know a clean way to find out if an object property exists? Here is my example:
var test = {
a : 'west',
b : {
a : 'rest'
},
d : {
a : 'pest'
}
};
// I want to access 'a' in 'c'
typeof test.c.a; // fails!
typeof it seems can't get past the fact that 'c' doesn't exist to check if 'a' exists inside it (I've also tried jQuery.type() which also fails in the same way - I would have thought it would have error checking inside that function).
In this example of course I could simply check if 'c' exists first but in my real situation I have a large and deep object and I need to dynamically retrieve data from any potential location so it would be nice if there were a ready-made solution which didn't necessitate having to use a try-catch.
Thanks in advance!
I can't vouch for any existing functionality in any js framework for finding nested properties, but you can certainly roll your own.
hasOwnProperty is part of the ECMA script standard.
if(test.hasOwnProperty("c"))
{
console.log("test.c = " + test.c);
}
If you are looking to find deeply nested properties, then you could roll your own function to check if the nested property exists, and if so, return it.
function hasNestedProperty(testObject, properties)
{
var maxDepth = properties.length;
var i, hasProperty = false;
var currObj = testObject;
while(hasProperty && i < maxDepth)
{
if(currObj.hasOwnProperty(properties[i])
{
currObj = currObj[properties[i]]);
i ++;
}
else
{
hasProperty = false;
}
}
return hasProperty;
}

Get JSON property from fully qualified string [duplicate]

This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
is it evil to use eval to convert a string to a function? [closed]
(4 answers)
Closed 10 years ago.
Say I have a JSON object like this:
var a = {
"b" : {
"c" : 1
}
}
is there a quick way to get at c when I know the string "b.c" ?
I guess I could split the string by dots then drill down into c from that but I was hoping there was a quick way to do this in one go.
like I was hoping maybe var c = a["b.c"] but that doesnt work
How about something like this, as you suggested using a split:
var a = {
"b" : {
"c" : 1
}
}
var n = "b.c".split(".");
var x = a;
for(var i = 0; i < n.length; i++){
x = x[n[i]];
}
//x should now equal a.b.c
Here is a working example
In the event that the path is not valid, there is some extra checking that should be done. As my code stands above, x will be undefined if the final part of the path is invalid (e.g "b.d"). If any other part of the path is invalid (e.g. "d.c") then the javascript will error.
Here is a modified example that will end the loop at the first instance of undefined, this will leave x as undefined and will ensure the javascript can continue to execute (no error!)...
var n = "d.c".split(".");
var x = a;
for (var i = 0; i < n.length; i++) {
x = x[n[i]];
if (typeof(x) == "undefined") {
break;
}
}
Here is an example of this in action
var a = {
"b" : {
"c" : 1
}
}
var c = "b.c".split(".").reduce(function(obj, key) {
return obj[key];
}, a);
alert(c)
See reduce. The link also show a how to implement shim for the browsers that doesn't support ES5. Notice that this code is simplified, assumes the keys are present in the objects.

Categories