【问题标题】:Get the array of values from array of objects using lodash使用 lodash 从对象数组中获取值数组
【发布时间】:2018-12-19 03:12:33
【问题描述】:

我有这个数组

    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?

【问题讨论】:

标签: arrays object lodash


【解决方案1】:

您可以简单地使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多