Open console to see the results (Press Command + Option + J (Mac) or Control + Shift + J (Windows, Linux, Chrome OS))
// Capitalise keys
function capitaliseKeys(obj) {
let newObj;
let entries = Object.entries(obj);
let mapEntries = entries.map((keyValue) => [
keyValue[0].toUpperCase(), keyValue[1]
]);
newObj = Object.fromEntries(mapEntries);
return newObj;
}
console.log(capitaliseKeys({ a: 1, b: 2, c: 3 }));
console.log(capitaliseKeys({ Hello: "hi" }));
console.log(capitaliseKeys({}));
// String to object
function stringToObject(str) {
let obj = {};
if (str.length === 0) {
return obj;
}
else {
let splitStr = str.split(",");
for (let i = 0; i < splitStr.length; i++) {
let parts = splitStr[i].split(':');
obj[parts[0]] = parts[1];
}
return obj;
}
}
console.log(stringToObject(""));
console.log(stringToObject("a:1,b:2,c:3"));
console.log(stringToObject("one:-1,two:hi there,three:what's that?"))
// Going shopping
function shoppingList(str) {
let obj = {};
if (str.length === 0) {
return obj;
}
else {
let splitStr = str.split(",")
for (let i = 0; i < splitStr.length; i++) {
let parts = splitStr[i].split(" ").reverse();
if (parts[1] == 0) {
splitStr.pop(splitStr[i]);
}
else {
obj[parts[0]] = Number(parts[1]);
}
}
return obj;
}
}
console.log(shoppingList("2 tomatoes, 1 egg, 3 pumpkins"));
console.log(shoppingList(""));
console.log(shoppingList("2 tomatoes, 1 egg, 0 pumpkins"));
// Map Object
function mapObject(obj, fn) {
let newObj;
let entries = Object.entries(obj);
let mapEntries = entries.map((keyValue) =>
[keyValue[0], fn(keyValue[1])]
);
newObj = Object.fromEntries(mapEntries);
return newObj;
}
console.log(mapObject({ a: 1, b: 2 }, (n) => n + 2));
console.log(mapObject(
{ greeting: 'hi there, ', goodbye: 'see you later, ' },
(s) => s + 'Yvonne'));