-1

I have this array

    this.complementaryFields = [
        {
            fieldName: 'complementaryLaser',
            label: 'Laser Hair Removal'
        },
        {
            fieldName: 'complementarySkin',
            label: 'Skin'
        },
        {
            fieldName: 'complementaryInjection',
            label: 'Cosmetic Injections'
        },
        {
            fieldName: 'complementaryNotSure',
            label: 'Not Sure'
        }
    ];

and I would like to create a new array out of it as below:

    this.complementaryFieldNames = [
        'complementaryLaser',
        'complementarySkin',
        'complementaryInjection',
        'complementaryNotSure'
    ];

How would you do it using lodash?

Negin Basiri
  • 1,305
  • 2
  • 26
  • 47
  • 1
    Without lodash : `complementaryFieldNames = complementaryFields.map({fieldName} => fieldName)` – Robby Cornelissen Dec 19 '18 at 03:18
  • Possible duplicate of [LoDash: Get an array of values from an array of object properties](https://stackoverflow.com/questions/28354725/lodash-get-an-array-of-values-from-an-array-of-object-properties) – Robby Cornelissen Dec 19 '18 at 03:22

1 Answers1

0

You can simply use lodash _.map to get that result:

const data = [{ fieldName: 'complementaryLaser', label: 'Laser Hair Removal' }, { fieldName: 'complementarySkin', label: 'Skin' }, { fieldName: 'complementaryInjection', label: 'Cosmetic Injections' }, { fieldName: 'complementaryNotSure', label: 'Not Sure' } ];

const result = _.map(data, 'fieldName')

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

With ES6 you can do same with Array.map and destructuring:

const data = [{ fieldName: 'complementaryLaser', label: 'Laser Hair Removal' }, { fieldName: 'complementarySkin', label: 'Skin' }, { fieldName: 'complementaryInjection', label: 'Cosmetic Injections' }, { fieldName: 'complementaryNotSure', label: 'Not Sure' } ];

const result = data.map(({fieldName}) => fieldName)

console.log(result)
Akrion
  • 18,117
  • 1
  • 34
  • 54