I have a simple array:
var arr = ['has_cats', 'has_dogs'];
and an object:
var obj = new Object();
and from the array I want to set object attributes:
for( i=0; i < arr.length; i++ ) {
if(!arr.hasOwnProperty(arr[i])) {
// set the object property
}
}
After looping I should be able to call obj.has_cats but I can’t seem to find a proper way to do it in javascript. In python I would call setattr(obj,arr[i], value). I figured that if objects have a hasOwnProperty they should also have a getOwnProperty and a setOwnProperty.
Any guidance?
The
hasOwnProperty()function tells you whether the named property exists as a direct property of the object, as compared to being an inherited property from somewhere in the object’s prototype chain. Theinoperator – used likeif (someProperty in someObject) {}– will tell you whether the object has that property anywhere in the prototype chain.You don’t need a corresponding
setOwnProperty()function because you can just say:I guess the idea of a corresponding
getOwnProperty()function kind of makes sense if you want a function that only returns a value if the specified property is a direct property, but then there wouldn’t be any way to indicate that the specified property wasn’t found because null, undefined, false, etc. are all legitimate potential values if the property is found. So to achieve that you need to do it as a two-step process usingif (hasOwnProperty()).But it doesn’t sound like that’s what you’re trying to do. If I understand you correctly, you just want some way to set a property where the property name is in a variable (in your case, an array element). You don’t make it clear what values you want associated to those properties, so I’ll just use
true.