Search code examples
arraysdictionarylodashtransform

How to get transform from object to specific key value pair using lodash?


Products: [
  {_id: 'xx1', name: 'p1', sku: 's1'},
  {_id: 'xx2', name: 'p2', sku: 's2'},
  {_id: 'xx3', name: 'p3', sku: 's3'}
]

I want to replace word '_id' with 'product', and to map to below result:

productArray = [ {product: 'xx1'}, {product: 'xx2'}, {product: 'xx3'} ];

I tried lodash code something like below but it just doesn't seem to work correctly:

let productArray = _.map(Products, '_id');

Can anyone help me on this? Thank you


Solution

  • Why would you even need to use lodash? Map will easily do the job.

    const products = [{
        _id: 'xx1',
        name: 'p1',
        sku: 's1'
      },
      {
        _id: 'xx2',
        name: 'p2',
        sku: 's2'
      },
      {
        _id: 'xx3',
        name: 'p3',
        sku: 's3'
      }
    ];
    
    const outProducts = products.map(x => {
      return {
        product: x._id
      }
    });
    
    console.log(outProducts);