Lodash使用优化

时间:2017-01-27 08:02:12

标签: javascript refactoring lodash

你好我有一个JSON对象如下:

{
  "serviceItemPriceList": [
    {
      "commissionalPrice": 2,
      "currencyType": {
        "type": "EUR",
        "languageKey": "enum.currency_type.EUR"
      },
      "id": 10,
      "officialPrice": 2,
      "vat": 5
    },
    {
      "commissionalPrice": 1,
      "currencyType": {
        "type": "TRY",
        "languageKey": "enum.currency_type.TRY"
      },
      "id": 9,
      "officialPrice": 1,
      "vat": 10
    }
  ]
}

让我们称之为obj ...我希望获得如下输出:

[
  {
    "id": 10,
    "currencyType": {
      "type": "EUR",
      "languageKey": "enum.currency_type.EUR"
    }
  },
  {
    "id": 9,
    "currencyType": {
      "type": "TRY",
      "languageKey": "enum.currency_type.TRY"
    }
  }
]

我有一个工作代码来实现这个目标:

lodash(obj.serviceItemPriceList).map(
  function (serviceItemPrice) {
    return lodash(serviceItemPrice).pick(['id', 'currencyType']).value();
  }
).value();

我的问题是:有没有更好/更短/更聪明的方法来做到这一点?

提前致谢!

3 个答案:

答案 0 :(得分:2)

使用Array.prototype.map()函数简短"纯" JavaScript解决方案:



var obj = {"serviceItemPriceList":[{"commissionalPrice":2,"currencyType":{"type":"EUR","languageKey":"enum.currency_type.EUR"},"id":10,"officialPrice":2,"at":5},{"commissionalPrice":1,"currencyType":{"type":"TRY","languageKey":"enum.currency_type.TRY"},"id":9,"officialPrice":1,"at":10}]};

var result = obj.serviceItemPriceList.map(function (o) {
    return {id: o.id, currencyType: o.currencyType};
});

console.log(result);




答案 1 :(得分:1)

您的解决方案已经足够短了,我建议您删除不必要的.value来电,因为您没有使用链接。

_.map(obj.serviceItemPriceList, item => _.pick(item, ['id', 'currencyType']));

答案 2 :(得分:0)

您可以拥有一组需要作为结果一部分的键,并使用.map + .reduce来返回新对象。

注意:拥有数组的目的是减少硬编码。



var obj={serviceItemPriceList:[{commissionalPrice:2,currencyType:{type:"EUR",languageKey:"enum.currency_type.EUR"},id:10,officialPrice:2,vat:5},{commissionalPrice:1,currencyType:{type:"TRY",languageKey:"enum.currency_type.TRY"},id:9,officialPrice:1,vat:10}]};

var returnKeyList = ["currencyType", "id"]
var r = obj.serviceItemPriceList.map(function(o){
  return returnKeyList.reduce(function(p,c){
    p[c] = o[c];
    return p;
  }, {})
});

console.log(r)




注意:currencyType是一个对象,对象通过引用传递,因此更改r[i].currencyType将反映在原始数组中。为避免这种情况,请尝试以下操作:



var obj={serviceItemPriceList:[{commissionalPrice:2,currencyType:{type:"EUR",languageKey:"enum.currency_type.EUR"},id:10,officialPrice:2,vat:5},{commissionalPrice:1,currencyType:{type:"TRY",languageKey:"enum.currency_type.TRY"},id:9,officialPrice:1,vat:10}]};

var returnKeyList = ["currencyType", "id"]
var r = obj.serviceItemPriceList.map(function(o){
  return returnKeyList.reduce(function(p,c){
    p[c] = typeof(o[c]) === "object" ? JSON.parse(JSON.stringify(o[c])) : o[c];
    return p;
  }, {})
});

console.log(r)