Open20

JSchallenger にチャレンジ - Fundamentals / Objects

cyamycyamy

Merge two objects with matching keys

Write a function that takes two objects as arguments
Unfortunately, the property 'b' in the second object has the wrong key
It should be named 'd' instead
Merge both objects and correct the wrong property name
Return the resulting object
It should have the properties 'a', 'b', 'c', 'd', and 'e'

https://www.jschallenger.com/javascript-fundamentals/javascript-objects/merge-objects-same-key

回答

function myFunction(x, y) {
  const { b, ...param } = y;
  return { ...x, ...param, d: b };
}
cyamycyamy

Swap object keys and values

Write a function that takes an object as argument
Somehow, the properties and keys of the object got mixed up
Swap the Javascript object's key with its values and return the resulting object

https://www.jschallenger.com/javascript-fundamentals/javascript-objects/swap-object-keys-values

回答

function myFunction(obj) {
  return Object.entries(obj).reduce((prev, current) => {
    const [key, value] = [...current];
    return {
      ...prev,
      [value]: key,
    };
  }, {});
}
cyamycyamy

Replace empty strings in object with null values

Write a function that takes an object as argument
Some of the property values contain empty strings
Replace empty strings and strings that contain only whitespace with null values
Return the resulting object

https://www.jschallenger.com/javascript-fundamentals/javascript-objects/replace-empty-strings-null

回答

function myFunction(obj) {
  return Object.entries(obj).reduce((prev, current) => {
    const [key, value] = [...current];
    return {
      ...prev,
      [key]: value.trim() === '' ? null : value,
    };
  }, {});
}
cyamycyamy

Extracting information from objects

Write a function that takes an object as argument containing properties with personal information
Extract firstName, lastName, size, and weight if available
If size or weight is given transform the value to a string
Attach the unit cm to the size
Attach the unit kg to the weight
Return a new object with all available properties that we are interested in

https://www.jschallenger.com/javascript-fundamentals/javascript-objects/extracting-information-ojects

回答

function myFunction(obj) {
  return {
    fn: obj.fn,
    ln: obj.ln,
    ...(obj.size && { size: `${obj.size}cm` }),
    ...(obj.weight && { weight: `${obj.weight}kg` }),
  };
}
cyamycyamy

Convert array to object with counter

Write a function that takes an array of numbers as argument
Convert the array to an object
It should have a key for each unique value of the array
The corresponding object value should be the number of times the key occurs within the array

https://www.jschallenger.com/javascript-fundamentals/javascript-objects/convert-array-to-objects-count

回答

function myFunction(a) {
  return a.reduce((prev, current) => {
    return {
      ...prev,
      [current]: (prev[current] ?? 0) + 1,
    };
  }, {});
}