Javascript: Check if something can have properties _added_ to it - javascript

EDIT: Made clearer that the need is to determine if I can add properties to a value, not if a value can have its own properties.
Is there a way to check if is possible to add properties to a value?
For example, if I have this code:
function test( value ) {
// return true if it is possible to add properties to value
}
Other than actually adding a property value to test, is there a reliable way to deduce if value is something that properties can be added to?
For example, I know an object can have properties and undefined can't, but I'm not keen on creating a list of known things that might not suffice in the future. Is something like instanceof object sufficient?

The list of values that do not have properties is quite short: undefined and null. Testing for those should be straightforward (value == null).
Note that all other primitives can have properties (through boxing), but as the boxed object gets lost immeadiately there is no sense in adding properties to them:
1..test = 1;
"test".test = 1;
Infinity.test = 1;
NaN.test = 1;
true.test = 1;
Symbol().test = 1;
1n.test = 1;
To check for non-primitives, typeof value === "object" can be used, but as null is also an object (a very special one, actually it counts as a primitive but typeof lies about that), you have to explicitly check for value !== null.
While you can usually add properties to objects, they can be frozen, then adding properties is useless, the same applies to Proxies.
const obj = {};
Object.freeze(obj);
obj.test = 1;
console.log(obj.test);
And as Proxies can't be detected, there is no way to find out wether a property can be added or not.

A simple idea (although it does not solve completely the case as per Jonas Wilms answer) may be:
function test(value) {
try {
if (value.p === undefined) {
value.p = 10;
if (value.p === undefined) {
return false;
}
delete value.p;
}
} catch(e) {
return false;
}
return true;
}
console.log('null: ' + test(null));
console.log('undefined: ' + test(undefined));
console.log('number: ' + test(10));
console.log('object: ' + test({a:10}));
var obj = { get p() { return false; }, set p(v) {} };
console.log('object with property name confict: ' + test(obj));

As pointed out by Jonas Wilms:
Bad usecase. You are just writing your next headache :)
I need to refactor my code so it doesn't need to jump through hoops.

Related

Is there a way to override Object to instantiate a property upon attempting to modify it?

I feel like the answer to this is a hard no in most languages I've used other than PHP, which at least used to have some odd corner cases with stuff like $someArray['nonexistentKey']++.
I'm basically looking to write a sparse object where each property is a numeric counter. The counters should return 0 if undefined and should automatically define themselves with a value of 0 if you try to increment them.
In other words, I want to override the generic Object getter to return 0 in all cases where it would return undefined... or perhaps define the property right there during the get and set it to 0.
So in theory, an overload for ANY property not yet defined would get initialize it at zero. For example this:
myObj['hugePrimeNumberToBaseXToString']++;
would then make it 1.
In the olden days I feel like some way with Object.__proto__ might have worked for this case...
I think what you want is a Proxy.
You can use a proxy to intercept property gets and return your own logic. In this case, return zero in the case of an undefined property.
// Hold the data
const target: { [key in string]: number } = {}
// Access the data
const proxy = new Proxy(target, {
get(target, prop, receiver) {
if (typeof prop === 'string') {
if (target[prop] === undefined) return 0
return target[prop]
}
return undefined
}
})
proxy['hugePrimeNumberToBaseXToString']++
console.log(proxy['hugePrimeNumberToBaseXToString']) //=> 1
Playground
Proxy is definitely the right answer, but I'd argue that tinkering with Object directly is much farther under the hood than you want to be.
Instead, I'd make a new, simple object type like so:
const Dictionary = function() {}
Dictionary.prototype.add = function(key) {
if (this.hasOwnProperty(key)) {
this[key] += 1;
} else {
this[key] = 1;
}
}
const dict = new Dictionary();
dict.add("apples");
console.log(dict.apples) // 1
dict.add("apples");
dict.add("bananas");
console.log(dict.apples, dict.bananas) // 2, 1
It's not quite what you wanted since you have to call add each time, but I'd take the three-character tradeoff for the sake of simplicity and extensibility.
Codepen

Checking if object is already in array not working

I am trying to check if an object is already in an array, following this answer here: How to determine if object is in array
I adjusted the function to suit my needs, and now it looks like this:
var _createDatesArray, _objInArray;
_objInArray = function(array, obj) {
var i;
i = 0;
while (i < array.length) {
console.log("array[i] == obj is ", array[i] === obj, " array[i] is ", array[i], " and obj is ", obj);
if (array[i] === obj) {
return true;
}
i++;
}
};
_createDatesArray = function(val) {
var result;
if (val != null) {
result = {
text: val
};
if (!_objInArray(scope.datesQuestion.dates, result)) {
scope.datesQuestion.dates.push(result);
}
return console.log(scope.datesQuestion.dates);
}
};
What I need to do, is basically see if the object is already in the array, and if is,t return true.
When debugging, the result of the console log is the following:
array[i] == obj is false array[i] is {text: "10/08/17"} and obj is
{text: "10/08/17"}
and the function says they are different (array[i] == obj is false) but they look the same to me.
I also checked the type of both, which is this:
typeof array[i] is "object"
typeof obj is "object"
can you help me with this? Why are they different? what can be different?
_createDatesArray is called when $scope of my angular app changes its value based on a ng-model, but I don't think this is relevant
They're two different objects with the same content. Comparing them with == or === will yield false.
Since you're using AngularJS, you can use angular.equals() instead to perform a deep comparison of the object's properties.
The objects you are comparing don't have the same reference, so == is returning false. See Object comparison in JavaScript for a more detailed explanation.
In this particular case, you could simply compare the text of dates to see if they are equivilant. However this wouldn't work for all objects like the function name suggests.
if (arr[i].text === obj.text)
Alternatively, you could create a method specific for checking if your array includes a given date and simplify it greatly using Array.prototype.some:
dateInArray = function (array, date) {
return array.some(function (arrayDate) {
return arrayDate.text === date.text
})
}
Or, more succinctly using ES6 arrow functions:
dateInArray = (array, date) => array.some(arrayDate => arrayDate.text === date.text)
array[i] === obj will return true ONLY if its the same object. In the link that you have referred the object being checked is the same object that is inserted in the array, thats why it returns true. In your case, you are creating a new object 'result' and adding the value in there. So the array does not contain the exact same object and hence returns false.
If 'text' is the only property in the object, instead of checking for the entire object you could check if the 'text' property in both the objects is same.
_objInArray = function(array, obj) {
var i;
i = 0;
while (i < array.length) {
if (array[i].text === obj.text) {
return true;
}
i++;
}
};
This happens because objects in JS are compared by reference, but not by values they have. But you need to compare objects by their value. So you need to get some third-party function or to write your own. One more option is to use angular built-in equals function.
angular.equals($scope.user1, $scope.user2);
For a better understanding you can read a good article on this subject here.

Looping through object in JavaScript

if(properties != undefined)
{
foreach(key in properties)
{
dialogProperty.key = property[key];
}
alert(dialogProperty.close);
}
How can I achieve/fix the above code? I think the above code is self explanatory.
I think you mean for rather than foreach. You should also stop key being global and use Object.prototype.hasOwnProperty:
if(properties != undefined)
{
for (var key in properties)
{
if (properties.hasOwnProperty(key) {
dialogProperty[key] = properties[key]; // fixed this variable name too
}
}
alert(dialogProperty.close);
}
NB Incorporated Kobi's fix too.
Assuming you're trying to copy all properties, you're probably looking for:
dialogProperty[key] = property[key];
dialogProperty.key is not dynamic, it sets the key property each time, the same way dialogProperty["key"] would.
properties && Object.keys(properties).forEach(function(key) {
dialogProperty[key] = properties[key];
});
console.log(dialogProperty.close);
The properties && check is to ensure that properties is not falsy.
The Object.keys call returns an array of all keys that the properties object has.
.forEach runs a function for each element in the array.
dialogProperty[key] = properties[key] set's the value of dialogProperty to be that of properties.

In JavaScript, is there an easier way to check if a property of a property exists?

Is there an easy way to natively determine if a deep property exists within an object in JavaScript? For example, I need to access a property like this:
var myVal = appData.foo.bar.setting;
But there is a chance that either foo, foo.bar, or foo.bar.setting has not been defined yet. In Groovy, we can do something like this:
def myVal = appData?.foo?.bar?.setting
Is there a similar way to do this in JavaScript, without having to write a custom function or nested if statements? I've found this answer to be useful, but was hoping there was a more elegant and less custom way.
I find this very convenient:
var myVal = (myVal=appData) && (myVal=myVal.foo) && (myVal=myVal.bar) && myVal.settings;
If a property exists, the next part of the sequence will be attempted.
When the expression before && evaluates to false, the next part of the expression will not be checked. If either of myVal.appData.foo.bar.settings is not defined, the value of myVal (undefined( will evaluate to false.
Sorry, it's not great:
var myVal = appData && appData.foo && appData.foo.bar && appData.foo.bar.setting;
Another option:
try {
var myVal = appData.foo.bar.setting;
} catch (e) {
var myVal = undefined;
}
The . operator is not really intended for accessing objects like this. Probably using a function would be a good idea.
The optional chaining operator (?.) was introduced in ES2020. Now, you should be able to write:
const myVal = appData?.foo?.bar?.setting
I find other approaches a bit immense. So, what would be the major drawback of the following approach:
// Pass the path as a string, parse it, and try to traverse the chain.
Object.prototype.pathExists = function(path) {
var members = path.split(".");
var currentMember = this;
for (var i = 0; i < members.length; i++) {
// Here we need to take special care of possible method
// calls and arrays, but I am too lazy to write it down.
if (currentMember.hasOwnProperty(members[i])) {
currentMember = currentMember[members[i]];
} else {
return false;
}
}
return true;
}
Basically, we define a method on the object (not necessarily) and that method takes the path to a nested object and returns existence confirmation, likeappData.pathExists("foo.bar.setting");
EDIT:
Check object[prop] == undefined is not semantically correct since it will return false even if the property is defined although its value is undefined; that is why I use hasOwnProperty to check is the property defined. This might not be important if one needs to just fetch the value.
If, after:
var myVal = appData.foo && appData.foo.bar && appData.foo.bar.setting;
myVal is not undefined, it will hold the value of appData.foo.bar.setting.
You can try this
var x = {y:{z:{a:'b'}}}
x && x.y && x.y.z && x.y.z.a //returns 'b'
This is not as good as the groovy expression but it works. The evaluation stops after encountering the first undefined variable.
var product = ...,
offering = (product||{}).offering,
merchant = (offering||{}).merchant,
merchantName = (merchant||{}).name;
if (merchantName)
displayMerchantName(merchantName);
http://osteele.com/archives/2007/12/cheap-monads
I just cooked this up so it might not work exactly right, I've also included two test cases.
function hasPropertyChain(o, properties) {
var i = 0,
currentPropertyChain = o;
if(!o) {
return false;
}
while(currentPropertyChain = currentPropertyChain[properties[i++]]);
return i - 1 === properties.length;
}
alert(hasPropertyChain({a:{b:{c:'a'}}}, ['a','b','c'])); // true
alert(hasPropertyChain({a:{b:{c:'a'}}}, ['a','b','c', 'd'])); // false

Check if an array item is set in JS

I've got an array
var assoc_pagine = new Array();
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
I tried
if (assoc_pagine[var] != "undefined") {
but it doesn't seem to work
I'm using jquery, I don't know if it can help
Thanks
Use the in keyword to test if a attribute is defined in a object
if (assoc_var in assoc_pagine)
OR
if ("home" in assoc_pagine)
There are quite a few issues here.
Firstly, is var supposed to a variable has the value "home", "work" or "about"? Or did you mean to inspect actual property called "var"?
If var is supposed to be a variable that has a string value, please note that var is a reserved word in JavaScript and you will need to use another name, such as assoc_var.
var assoc_var = "home";
assoc_pagine[assoc_var] // equals 0 in your example
If you meant to inspect the property called "var", then you simple need to put it inside of quotes.
assoc_pagine["var"]
Then, undefined is not the same as "undefined". You will need typeof to get the string representation of the objects type.
This is a breakdown of all the steps.
var assoc_var = "home";
var value = assoc_pagine[assoc_var]; // 0
var typeofValue = typeof value; // "number"
So to fix your problem
if (typeof assoc_pagine[assoc_var] != "undefined")
update: As other answers have indicated, using a array is not the best sollution for this problem. Consider using a Object instead.
var assoc_pagine = new Object();
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
var assoc_pagine = new Array();
assoc_pagine["home"]=0;
Don't use an Array for this. Arrays are for numerically-indexed lists. Just use a plain Object ({}).
What you are thinking of with the 'undefined' string is probably this:
if (typeof assoc_pagine[key]!=='undefined')
This is (more or less) the same as saying
if (assoc_pagine[key]!==undefined)
However, either way this is a bit ugly. You're dereferencing a key that may not exist (which would be an error in any more sensible language), and relying on JavaScript's weird hack of giving you the special undefined value for non-existent properties.
This also doesn't quite tell you if the property really wasn't there, or if it was there but explicitly set to the undefined value.
This is a more explicit, readable and IMO all-round better approach:
if (key in assoc_pagine)
var is a statement... so it's a reserved word... So just call it another way.
And that's a better way of doing it (=== is better than ==)
if(typeof array[name] !== 'undefined') {
alert("Has var");
} else {
alert("Doesn't have var");
}
This is not an Array.
Better declare it like this:
var assoc_pagine = {};
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
or
var assoc_pagine = {
home:0,
about:1,
work:2
};
To check if an object contains some label you simply do something like this:
if('work' in assoc_pagine){
// do your thing
};
This worked for me
if (assoc_pagine[var] != undefined) {
instead this
if (assoc_pagine[var] != "undefined") {
TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)
function arrayIndexExists(array, index){
if ( typeof index !== 'number' && index === parseInt(index).toString()) {
index = parseInt(index);
} else {
return false;//to avoid checking typeof again
}
return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}
The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.
Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)
Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.
This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);
var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"
This shows that associative keys are not used to access elements in the array, but for properties of the object.
foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3
This shows that checking typeof doesn't allow you to see if an element has been set.
var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined
This shows the exception I mentioned above and why you can't just use parseInt();
If you want to use associative arrays, you are better off using simple objects as other answers have recommended.
if (assoc_pagine.indexOf('home') > -1) {
// we have home element in the assoc_pagine array
}
Mozilla indexOf
function isset(key){
ret = false;
array_example.forEach(function(entry) {
if( entry == key ){
ret = true;
}
});
return ret;
}
alert( isset("key_search") );
The most effective way:
if (array.indexOf(element) > -1) {
alert('Bingooo')
}
W3Schools

Categories

Resources