Obj Problems
Obj Problems
by Farzad YZ
JavaScript
/* Problem #2: Write a function that receives a object as the argument and inverts it.
Example: */
const map = {
a: ["z"],
b: ["x", "y"],
c: ["w", "z"]
};
/* Invert(map); ==> {
z: [‘a’, ‘c’],
x: [‘b’],
y: [‘b’],
w: [‘c']
} */
/* Problem #4: Write a function named pick that accepts an object as the 1st argument and a list of keys as the 2nd argument and returns a subset of that object that only contains the picked keys and their corresponding values.
example: */
const object4 = {
'a': 1,
'b': '2',
'c': 3
};
/* pick(object, ['a', 'c']); // {a: 1, c: 3} */
function pick(object, keys) {
const newObject = {};
keys.map(key => newObject[key] = object[key]);
console.log(newObject, "pick")
return newObject;
}
pick(object4, ['a', 'c']);
/* Problem #5: Write a function named omit that accepts an object as the 1st argument and a list of keys as the 2nd argument and returns all the given keys and their values from the object.
example: */
const object5 = {
'a': 1,
'b': '2',
'c': 3
};
/* omit(object, ['a', 'c']); // {b: 2} */
function omit(object, keys) {
const newObject = {};
const objectKeys = Object.keys(object);
objectKeys.map(key => keys.includes(key) ? [] : newObject[key] = object[key])
console.log(newObject, "omit")
return newObject;
}
omit(object5, ['a', 'c']);