当结果应该是Map时获得数组结果?

时间:2019-10-07 15:22:53

标签: javascript node.js

我正在尝试将MAP用于node.js程序,但最终结果却在数组中,但我需要在map中。我已经写了一些代码来使用map,但是它不能按预期工作。

请在下面找到程序

function CreateProduceMVPRateAsset(data, callback) {
    var ProducePRICE = {};

    var MVPPRICE = [];
    var MVPPRICE_BS = {};
    var MVPPRICE_LB = {};
    const walletPath = path.join(process.cwd(), 'wallet');
    const wallet = new FileSystemWallet(walletPath);
    console.log(`Wallet path: ${walletPath}`);
    console.log('Data', data);
    console.log('Username', data.username);
    var PRODUCENAME = data.PRODUCE;

    var COUNTRY = data.COUNTRY;
    var STATE = data.STATE;
    var MVPRATES = data.MVPRATES;
    console.log('MVPRATERATE', MVPRATES);
    // here I need help
    const MVPRATE = new Map(MVPRATES);

    for (const [k, v] of MVPRATE.entries()) {
        console.log('Inside map', k, v);
        MVPPRICE = v.RATE; // should go in  MVPPRICE

        var Value = MVPPRICE[0].value; // want to get first element value from MVPPRICE array
        console.log('Value', Value);

        var value_lb = Value / 40;
        console.log('value_lb', value_lb);

        value_lb = Number(value_lb.toFixed(4));

        console.log('If the value of BS provided controller come here');

        MVPPRICE_LB.Value = value_lb;
        MVPPRICE_LB.QuantityUnit = 'LB';
        MVPPRICE_LB.uidisplay = false;
        MVPPRICE_LB.CurrencyUnit = 'USD';

        MVPPRICE.push(MVPPRICE_LB);
        ProducePRICE.MVPPRICE = MVPPRICE;

        ProducePRICE.PRODUCENAME = PRODUCENAME;
        ProducePRICE.STATE = STATE;
        ProducePRICE.COUNTRY = COUNTRY;
        console.log('ProducePRICE', ProducePRICE); // whatever result getting it should be map however getting in array.
    }
}

我使用邮递员发送的JSON结构

{
"username": "admin2",
  "PRODUCE": "Apple",
  "STATE": "MI",
  "COUNTRY": "US",
  "MVPRATES": {
    "fuji": {
      "VARIETY": "fuji",
      "RATE": [
        {
          "UNIT": "Bussel",
          "CURRENCY": "USD",
          "VALUE": 10.25,
          "UIDISPLAY": true
        }
      ]
    },
    "gala": {
      "VARIETY": "gala",
      "RATE": [
        {
          "UNIT": "Bussel",
          "CURRENCY": "USD",
          "VALUE": 10.25,
          "UIDISPLAY": true
        }
      ]
    }
  }
}

我得到的输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

@SudhakarRS是正确的,您正在获取MAP,只是将您的值存储在MVPRATE数组中,这看起来像是您的意图,看到您在此处推送:

MVPPRICE.push(MVPPRICE_LB);

我在评论中提到了,但是我认为发生的事情是Map不适用于递归,因此当它看到MVPPRICE时,会将您的value数组视为值,而不是map的一部分。

我认为您可以通过以下方法解决此问题:

MVPPRICE.concat(MVPPRICE_LB);
ProducePRICE.MVPPRICE = new Map(MVPPRICE)