javascriptmappingspread-syntax

How to decipher mapping function to key value pairs


Good morning. I'm trying to decipher what this function is doing as I'm new to JS and breaking it down line by line. I also tried putting the function into Babel to see if it would be more explicit.

const t = objArray =>     
  Object.assign(
    {},
    ...objArray.map(
      ({ v, k }) => ({ [k]: v     
    }))
  );

This is what I believe is occurring:

const t = objArray =>     
  Object.assign(
    {},
  1. an array object is being cloned with all properties of objArray
...objArray.map(
      ({ v, k }) => ({ [k]: v     
    }))
  );
  1. This is where I get a little confused. Is objArray being mapped to a new array object where each array element holds a key and val?

Any help and tips to decipher these complex functions are greatly appreciated. Thank you


Solution

  • This function takes an array of objects and turns it into a dictionary.

    The array of objects have this shape:

    [
      {
        v, // 'v' holds some value
        k // 'k' holds some value
      },
    ...
    ]
    

    For each object in the array the function takes the value k and tunrs it into a key. The value v becomes the associated value.

    If the k and v are numbered, here is what you obtain in the dictionary:

    {
      [k1]: v1,
      [k2]: v2,
      [k3]: v3,
      ...
    }