About
Object key management.
Articles Related
Management
Set an object key via a variable
let obj = {};
let propertyName = "myKey";
obj[propertyName] = `value for property ${propertyName}`;
console.log(obj);
Get value
let obj = {
name: "foo"
}
console.log("With the Object utility class: "+Object(obj)["name"]);
console.log("With the dot notation: "+ obj.name);
console.log("With the array notation: "+ obj["name"]);
Exist
In Method
Check all properties (also the inherited one)
var myObj = {myProp:3} ;
if ("myProp" in myObj) {
console.log("Yes, i have that key with the value "+myObj["myProp"]);
}
if (!("myFakeProp" in myObj)) {
console.log("No, i haven't that key");
}
hasOwnProperty
check only the direct properties of the object and not the inherited one from a prototype
var myObj = {myProp:3} ;
if (myObj.hasOwnProperty("myProp")) {
console.log("Yes, i have that key with the value "+myObj["myProp"]);
}
Name
A property name must not begin with a number
Loop Keys: For … in
- Javascript - For Statement get the key of the object and from the prototype
var person = {name: "Nicolas", length: 180};
function ColoredPerson() {
// Rode piet !
this.color = "red";
}
ColoredPerson.prototype = person;
var coloredPerson = new ColoredPerson();
var propSource;
for (var prop in coloredPerson) {
if (coloredPerson.hasOwnProperty(prop)) {
propSource = "object";
} else {
propSource = "prototype";
}
console.log("The property " + prop + " (value:" + coloredPerson[prop] + ") is a property from the " + propSource + ".");
}
Keys
Object.keys
en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys get the key of the object (not from the prototype).
Object.keys(obj)
Example:
var person = {name: "Nicolas", length: 180};
function ColoredPerson() {
// Rode piet !
this.color = "red";
}
ColoredPerson.prototype = person;
var coloredPerson = new ColoredPerson();
console.log("Object.keys will not list the prototype property");
var keys = Object.keys(coloredPerson);
for (var i = 0; i < keys.length; i++) {
console.log("The property " + keys[i] + " (value:" + coloredPerson[keys[i]] + ") is a property from the objects.");
}
Length
console.log("The number of key/properties in the global object is "+ Object.keys(this).length);