Unwind object

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 }]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Function property names

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

    JavaScript, Object · Oct 20, 2020

  • Map an object to an array

    Maps an object to an object array, using the provided mapping function.

    JavaScript, Object · Feb 5, 2023

  • Compact object

    Deeply removes all falsy values from an object or array.

    JavaScript, Object · Nov 27, 2020