【问题标题】:_.map values from object into field names for another object?_.map 值从对象到另一个对象的字段名称?
【发布时间】:2018-02-06 00:57:32
【问题描述】:

努力用词汇来正确地问这个问题,所以这是我的代码,并附有以下解释:

import _ from 'lodash';
import React, { Component } from 'react';

export default class Base extends Component {

    render() {
        const { cr, p } = this.props;
        return (
            <tr className='bq-bottom-border'>
                <td className='bq-column-border' colSpan='3'>Base</td>
                <td>{cr.BaseN}</td>
                <td>{'$' + (cr.Base10/1000).toFixed(1)}</td>
                <td>{'$' + (cr.Base25/1000).toFixed(1)}</td>
                <td>{'$' + (cr.BaseMedian/1000).toFixed(1)}</td>
                <td>{'$' + (cr.BaseMean/1000).toFixed(1)}</td>
                <td>{'$' + (cr.Base75/1000).toFixed(1)}</td>
                <td>{'$' + (cr.Base90/1000).toFixed(1)}</td>
            </tr>
        );
    }
}

所以我想重构它。 BaseN 是整数,Base10Base25 等是百分位数。我正在设置 FE 以允许用户自己选择百分位数,因此需要摆脱硬编码。

为此,我将1025 等内容移动到从父级传递下来的状态对象p 中。它看起来像这样:

percentiles = {
    p1: 10,
    p2: 25,
    p3: 50,
    p4: 75,
    p5: 90
}

然后我想执行以下操作:

_.map(percentiles, p => {
    'Base' + p
}

要生成在 &lt;td&gt; 中使用的字段名称,您会看到:cr.Base10cr.Base25 等。cr. 本身就是一个对象,每 5 个百分位数都有。

这是我无法理解如何实现它的地方。我无法执行以下操作:

_.map(percentiles, p => {
    <td>{'$' + (cr.Base{p}/1000).toFixed(1)}</td>
}

有没有办法做到这一点?

编辑

所以我正在尝试这个,其他一些变体,它返回为未定义,所以不确定我做错了什么......

testRender(percentiles, cr) {
    _.map(_.values(percentiles), p => {
        console.log(cr.Base + {p});
        console.log(cr.Base + p);
    })
}

或者:

testRender(percentiles, cr) {
    _.map(_.values(percentiles), p => {
        let field = 'Base' + p;
        console.log(cr.field);
        console.log(cr + '.field');
    })
}

我可以做一个console.log(cr.Base10);,它按预期工作。

【问题讨论】:

    标签: javascript reactjs lodash


    【解决方案1】:

    使用 Lodash,您可以从百分位数对象的属性创建一个数组:

    让 _percentiles = _.values(percentiles);

    然后您可以在对“map”的调用中遍历它

    【讨论】:

    • 您好,感谢您的回复。还是有问题。请查看我修改后的问题。
    【解决方案2】:

    好的,Ben Smith 的回答和这个 link 帮助我得出了答案:

    基本上需要将语句包装在eval()中以得出解决方案:

    testRender(percentiles, cr) {
        _.map(percentiles, p => {
            let field = eval('cr.Base' + (p == 'n' ? 'N' : p));
            console.log(field);
        })
    }
    

    字段的实际值记录在控制台中。

    【讨论】:

    • 很高兴您找到了解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2021-06-24
    • 2011-02-07
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多