Unwind object

Angelos Chalaris · JavaScript, Object · Apr 18, 2022

Produces an array of objects from an object and one of its array-valued properties.

  • Use object destructuring to exclude the key-value pair for the specified key from the object.
  • Use Array.prototype.map() for the values of the given key to create an array of objects.
  • Each object contains the original object's values, except for key which is mapped to its individual values.
const unwind = (key, obj) => {
  const { [key]: _, ...rest } = obj;
  return obj[key].map(val => ({ ...rest, [key]: val }));
unwind('b', { a: true, b: [1, 2] }); // [{ a: true, b: 1 }, { a: true, b: 2 }]

Would you like to help us improve 30 seconds of code?Take a quick survey

Recommended snippets

  • Function property names

    JavaScript, Object

    Gets an array of function property names from own (and optionally inherited) enumerable properties of an object.

  • Compact object

    JavaScript, Object

    Deeply removes all falsy values from an object or array.

  • Omits the key-value pairs corresponding to the keys of the object for which the given function returns falsy.