使用lodash映射JSON对象

时间:2016-12-23 19:42:16

标签: jquery django lodash

我尝试使用lodash映射JSON对象。我按如下方式调用json对象:

var json = (function() {
var json = null;
$.ajax({
    'async': false,
    'global': false,
    'url': "{% url 'api_temp_income_statement' asset_details.id %}",
    'datatype': "json",
    'success': function (data) {
        json = data;
    }
});
return json;

})

返回一个如下所示的JSON对象:

[{"model": "tempincomestatement",
  "pk": 3,
  "fields": {"income_period": "2016-01-31", "lease_income_collected": "994174.0000", "storage_income_collected": "236216.0000", "tax_income_collected": "131020.0000", "other_income_collected": "0.0000"}
},... ]

我试图创建一个具有收入期:剩余字段关系的地图,所以

 "2016-01-31" : {"lease_income_collected" : "994174", ... }

阅读文档,它并没有真正解决如何解决这个问题......我将如何实现这一目标?

3 个答案:

答案 0 :(得分:1)

使用_.chain(data) .map('fields') .keyBy('income_period') .mapValues(function(val) { return _.omit(val, 'income_period'); }) .value(); 按键将数组转换为对象

{{1}}

答案 1 :(得分:0)

您可以使用Object.keys()计算属性名称Array.prototype.reduce()



var data = [{
  "model": "tempincomestatement",
  "pk": 3,
  "fields": {
    "income_period": "2016-01-31",
    "lease_income_collected": "994174.0000",
    "storage_income_collected": "236216.0000",
    "tax_income_collected": "131020.0000",
    "other_income_collected": "0.0000"
  }
}];

var [, ...fields] = Object.keys(data[0].fields);
var res = {
  [data[0].fields.income_period]: fields.reduce((obj, prop) => 
  (obj[prop] = data[0].fields[prop], obj), {})
};

console.log(res);




答案 2 :(得分:0)

您可以使用_.map

var json = [{"model": "tempincomestatement",
          "pk": 3,
          "fields": {"income_period": "2016-01-31", "lease_income_collected": "994174.0000", "storage_income_collected": "236216.0000", "tax_income_collected": "131020.0000", "other_income_collected": "0.0000"}
         }, {"model": "1",
             "pk": 3,
             "fields": {"income_period": "2016-01-31", "lease_income_collected": "994174.0000", "storage_income_collected": "236216.0000", "tax_income_collected": "131020.0000", "other_income_collected": "0.0000"}
            }, {"model": "1",
             "pk": 3,
             "fields": {"lease_income_collected": "994174.0000", "storage_income_collected": "236216.0000", "tax_income_collected": "131020.0000", "other_income_collected": "0.0000"}
            } ];
var result = _.map(json, function(obj) {
  if (obj.fields.income_period !== undefined) {
    var result = {};
    var eleName = obj.fields.income_period;
    delete obj.fields.income_period;
    result[eleName] = obj.fields;
    return result;
  }
});
result = _.filter(result, Boolean);

console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>