Lodash链接?

时间:2018-02-14 15:56:08

标签: javascript json lodash chaining

我有一个看起来像这样的JSON对象:

{
      "ReceiptNumber": 2129,
      "ReceiptResult": 1,
      "ReceiptAmount": "6756",
      "ReceiptData": [
        {
          "LineNum": "JonSnow",
          "Data": "Standard data for Jon Snow"
        },
        {
          "LineNum": "HarryPotter",
          "Data": "Standard data for Harry Potter"
        },
        {
          "LineNum": "MickyMouse",
          "Data": "Standard data for Micky Mouse"
        }
      ],
      "ReceiptReference": "22e06e66-e711-bd14-7874a-002219649f24"
}

我正在尝试将其转换为:

{
    "receiptNumber": 2129,
    "receiptResult": 1,
    "receiptAmount": "6756",
    "receiptData": {
        "jonSnow": "Standard data for Jon Snow",
        "harryPotter": "Standard data for Harry Potter",
        "mickyMouse": "Standard data for Micky Mouse"
    },
    "receiptReference": "22e06e66-e711-bd14-7874a-002219649f24"
}

我正在起诉的方法:

  getFromReceipt(result): void {
    result.ReceiptData = _.assign({}, ...result.ReceiptData.map(el => {
      return { [_.camelCase(el.LineNum)]: el.Data }
    }));

    this.camelCaseAllKeys(result);
  }

  camelCaseAllKeys(result) {
    return _.mapKeys(result, (v, k) => _.camelCase(k.toString()));
  }

有没有办法简化这些方法,并最终通过链接在一个函数中完成所有操作?

1 个答案:

答案 0 :(得分:0)

评论太长了。

您在一个函数中将多个问题混为一谈:

  1. 展平ReceiptData
  2. camelcase the keys
  3. 目前尚不清楚这些东西应该是同一个功能:虽然它是较短的代码,但却是虚假的经济。一旦你通过minifier + gzip运行它,差异可以忽略不计,虽然更短的代码通常更容易阅读混淆不同的问题使得它更难。除非您的数据集真的很大(在这种情况下,您为什么要在客户端处理它?)对运行时性能的影响可以忽略不计。

    所以我会推荐更像这样的东西:

    let data = howeverYouGotTheData;
    let flattenReceiptData = o => {
      o.ReceiptData = o.ReceiptData.reduce((acc, record) => {
        acc[_.camelCase(record.lineNum)] = record.Data;
        return acc;
      }, {});
      return o;
    };
    
    let camelCaseKeys = o => {
      return Object.entries(o).reduce((acc, [k, v]) => {
        acc[_.camelCase(k)] = v;
        return acc;
      }, {});
    };
    
    // _.flow is lodash's implementation of left composition
    let flattenAndCase = _.flow(flattenReceiptData, camelCaseKeys);
    
    let result = flattenAndCase(data);
    

    现在问题被正确分开,一切都清楚地命名并且易于阅读,等等。如果你真的想要打高尔夫,你可以使用这样的标准技巧:

    let cc = _.camelCase;
    let flattenRD = o => (o.ReceiptData = o.ReceiptData.reduce((a, x) => (a[cc(x.lineNum)] = x.Data, a), {}));
    

    等。我使用逗号运算符来压缩赋值并返回一个表达式,避免需要Object.assign