Javascript - (Object) Key

About

Object key management.

A key is also known as a property name :)

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

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);





Discover More
Javascript - (Object) Property

Property Management of an object A property has : a key and a value Property names can be Reference/Operators/Object_initializerdynamic Reference/Operators/delete A property may be...
Javascript - Object

object in javascript An object is a data type in Javascript. An object follows a json data structure with key that holds property value. The value may be of a variable or a function In JavaScript, a...



Share this page:
Follow us:
Task Runner