Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript setattr or setOwnProperty

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?

like image 871
Romeo M. Avatar asked Jul 25 '26 19:07

Romeo M.


2 Answers

"I figured that if objects have a hasOwnProperty they should also have a getOwnProperty and a setOwnProperty"

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. The in operator - used like if (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:

someObject[someProperty] = someValue;

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 using if (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.

var arr = ['has_cats', 'has_dogs'];

var obj = {}; // note {} is generally preferred to new Object();

for(var i=0; i < arr.length; i++ ) {
  // if the property doesn't already exist directly on
  // the object
  if(!obj.hasOwnProperty(arr[i])) {
     // set the object property
     obj[arr[i]] = true;
  }
}

// can access with bracket notation
alert(obj["has_cats"]);

// can access with dot notation
alert(obj.has_cats);
like image 65
nnnnnn Avatar answered Jul 28 '26 09:07

nnnnnn


You can set the value via:

for(i = 0; i < arr.length; i++ ) {
        if(!obj.hasOwnProperty(arr[i])) {
                obj[arr[i]] = 'value';
        }
}
like image 44
mikeycgto Avatar answered Jul 28 '26 09:07

mikeycgto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!