Module 1 - Objects 1, 2, 3 Flashcards
Write a function called “getProperty”. Given an object and a key, “getProperty” returns the value of the property at the given key. Notes:
If there is no property at the given key, it should return undefined.
function getProperty(obj, key) {
if(obj) {
return obj[key];
} else {
return undefined;
}
}
Write a function called “addProperty”. Given an object, and a key, “addProperty” sets a new property on the given object with a value of true.
**function addProperty(obj, key) { var myObj = {}; obj[key] = true; return obj; }**
Write a function called “removeProperty”. Given an object and a key, “removeProperty” removes the given key from the given object.
function removeProperty(obj, key) {
delete obj[key];
return obj;
}
Write a function called “addFullNameProperty”.
Given an object that has a “firstName” property and a “lastName” property, “addFullNameProperty” returns a “fullName” property whose value is a string with the first name and last name separated by a space.
function addFullNameProperty(obj) {
obj.fullName = obj.firstName + ‘ ‘ + obj.lastName;
return obj;
}
Write a function called “addObjectProperty”.
Given two objects and a key, “addObjectProperty” sets a new property on the 1st object at the given key. The value of that new property is the entire 2nd object.
function addObjectProperty(obj1, key, obj2) {
obj1[key] = obj2;
}
Write a function called “isPersonOldEnoughToDrinkAndDrive”.
Given a “person” object, that contains an “age” property, “isPersonOldEnoughToDrinkAndDrive” returns whether the given person is old enough to legally drink and drive in the United States.
Notes:
The legal drinking age in the United States is 21.
The legal driving age in the United States is 16.
It is ALWAYS illegal to drink and drive in the United States.
function isPersonOldEnoughToDrinkAndDrive(person) {
return false;
}
Write a function called “isPersonOldEnoughToDrive”.
Given a “person” object, that contains an “age” property, “isPersonOldEnoughToDrive” returns whether the given person is old enough to drive.
function isPersonOldEnoughToDrive(person) {
if (person.age >=16) {
return true;
} else {
return false;
}
}
Write a function called “isPersonOldEnoughToVote”.
Given a “person” object, that contains an “age” property, “isPersonOldEnoughToVote” returns whether the given person is old enough to vote.
function isPersonOldEnoughToVote(person) {
if (person.age >=18) {
return true;
}else{
return false;
}
}
Write a function called “addArrayProperty”.
Given an object, a key, and an array, “addArrayProperty” sets a new property on the object at the given key, with its value set to the given array.
function addArrayProperty(obj, key, arr) {
obj[key] = arr;
return obj;
}