1

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

Trav
  • 135
  • 1
  • 2
  • 11
  • `[ { "k": "key1", "v": "value1" }, { "k": "key2", "v": "value2" } ]` -> `{ "key1": "value1", "key2": "value2" }` – Andreas Nov 04 '19 at 15:07
  • 1
    `({ v, k })` -> [Destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), `...objArray` -> [Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), `{ [k]: ... }` -> [Object initializer -> Computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) – Andreas Nov 04 '19 at 15:12
  • [How do I convert array of Objects into one Object in JavaScript?](https://stackoverflow.com/questions/19874555/how-do-i-convert-array-of-objects-into-one-object-in-javascript) – Andreas Nov 04 '19 at 15:21

1 Answers1

1

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,
  ...
}
Baboo
  • 4,008
  • 3
  • 18
  • 33