使用lodash从对象数组中获取值数组

时间:2018-12-19 03:12:33

标签: arrays object lodash

我有这个数组

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

,我想从中创建一个新数组,如下所示:

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

您将如何使用lodash?

1 个答案:

答案 0 :(得分:0)

您可以简单地使用lodash _.map获得该结果:

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>

使用ES6,您可以对Array.map和销毁进行同样的操作:

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)