Skip to content

Object Syntax

const myCat = {
firstName: 'Pedro',
'Middle Name': 'P.', // invalid identifier
lastName: 'Hofer',
age: 4,
color: 'black',
purrPurr: function (purr) {
console.log(purr);
},
favoriteFood: ['Animonda', 'ZooRoyal', 'Whiskas'],
}
myCat.firstName; // Pedro
// only bracket notation works with invalid identifiers:
myCat['Middle Name']; // P.
myCat.lastName; // Hofer
myCat.age; // 4
myCat.color; // black
// this function is the value of the property purrPurr
// since it is contained in an object, we call it method
myCat.purrPurr('Pedro says: Meooooow!!!');
myCat['purrPurr']('Mrrrrow!!');
myCat.favoriteFood[2];
// get the value (?)
const age = myCat.age;
const ageBracketNotation = myCat['age']; // mind the '' !!!
// get the value of a property through a variable:
// (why do we want to do this?)
const foodToBuy = 'favoriteFood';
const pedrosFood = myCat[foodToBuy]; // why no '' - bc. it is a constant???
console.log("Pedro loves " + pedrosFood + ".");
// with dot notation
myCat.favoriteCanOpener = 'Axel';
// with bracket notation
myCat['secondFavoriteCanOpener'] = 'Birgit';

delete.myObject.property

delete myCat['Middle Name'];

Wenn man Objekte erstellt, kann es passieren, dass man einer Eigenschaft eine Variable zuweist, die zufällig genauso heißt wie die Eigenschaft selbst. Dann kann man den Zuweisungsteil weglassen.

const fullName = 'Zell Liew';
const Zell = {
fullName: fullName,
};
// mit Shorthand:
const ZellShorthand = {
fullName,
}
// Declaring a method with a function expression:
const Pedro = {
purrMyName: function () {
console.log('Mrrrrrow Pedro!');
}
}
// Method shorthands allow to omit the [: function] part:
const PedroShort = {
purrMyName() {
console.log('Prrrrredro!');
}
};

3. Declaring a property name through a variable

Section titled “3. Declaring a property name through a variable”

… das versteh ich nicht und das ergibt auch immer undefined …

const property = 'myName';
obj[property] = 'Bibs';
// Computed object property names lets you create objects with
// variables as property keys. To do so, wrap the property with
// square brackets (dynamic variables).
const property2 = 'pedroName';
const cat = {
[property2]: 'Pedro Hofer',
};
// changing the property while creating it:
const property3 = 'axelName';
const person2 = {
[property3]: 'Axel',
['full' + property3]: 'Axel Riese',
}
// nix verstehen und ergibt undefined
const property4 = 'name';
const person = {
[property]: 'Zell',
['full + property']: 'Zell Liew',
}
console.log(person.fullname);