Search code examples
javascriptlodashunpivot

How to unpivot a collection/array with Lodash.js?


I'm a beginner in JavaScript, and I would like to unpivot a collection/array.

I have a collection/array like this :

[
  { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
  { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
]

and I would like to transform my collection/array to get something like this :

var a = [
  { 'produit': 'a', 'attribute': 'color', 'value': 'white' }, 
  { 'produit': 'a', 'attribute': 'material', 'value': 'leather' }, 
  { 'produit': 'b', 'attribute': 'color', 'value' :'black' },
  { 'produit': 'b', 'attribute': 'material', 'value': 'wool' }
]

I try to find something in the documentation of lodash.js, but I can't figure out how to do it.


Solution

  • You can use _.flatMap(), by destructuring the produit key for each object and then mapping the keys/values of the remaining object to a new object which includes the produit key, the key as the attribute key and the value as the value key:

    const arr = [
      { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
      { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
    ];
    
    const res = _.flatMap(
      arr,
      ({produit, ...r}) => _.map(_.entries(r), ([attribute, value]) => ({produit, attribute, value}))
    );
    
    console.log(res);
    <script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

    JS has many inbuilt array functions these days, so the above can also be achieved in vanilla JS using similar methods:

    const arr = [
      { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
      { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
    ];
    
    const res = arr.flatMap(
      ({produit, ...r}) => Object.entries(r).map(([attribute, value]) => ({produit, attribute, value}))
    );
    
    console.log(res);
    <script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>