简体   繁体   English

用lodash或下划线进行Javascript对象转换

[英]Javascript object transform with lodash or underscore

I have an many object with structure of: 我有一个结构很多的对象:

[{
     n_vId: 1,
     s_vName: 'test',
     d_date: '2016-03-15 00:00:00'
     f_a: 0,
     f_b: 0,
     f_c: 0,
     f_d: 4,
     f_e: 0,
     f_f: 0.1,
     f_g: 0
},
{
     n_vId: 2,
     s_vName: 'test',
     d_date: '2016-03-15 00:15:00'
     f_a: 1,
     f_b: 1,
     f_c: 0,
     f_d: 4,
     f_e: 0,
     f_f: 0.1,
     f_g: 0
}]

i want this object transform to 我想将此对象转换为

a = [
     {
         date: '2016-03-15 00:00:00',
         a: 0
     },
     {
         date: '2016-03-15 00:15:00',
         a: 1
     }
]

b = [
     {
         date: '2016-03-15 00:00:00',
         b: 0
     },
     {
         date: '2016-03-15 00:15:00',
         b: 1
     }
]
...

i can transform that. 我可以改变它。 but my process is so complicated i think. 但我认为我的过程是如此复杂。 so, would you advice me right process? 所以,您能建议我正确的程序吗? now i use lodash but can use underscore or another js modules. 现在我使用lodash,但可以使用下划线或其他js模块。

You can simply use map: 您可以简单地使用map:

a = data.map(function(i) {
        return {date: i.d_date, a: i.f_a};
    });

b = data.map(function(i) {
        return {date: i.d_date, b: i.f_b};
    });

Seems simple enough to me. 对我来说似乎很简单。

Take a look at this npm module https://github.com/gabesoft/trans 看看这个npm模块https://github.com/gabesoft/trans

   var trans = require('trans');
   var results = trans(data)
     .mapff('d_date', 'date')
     .mapff('f_a', 'a')
     .pick('date', 'a')
     .value();

As others have said, you don't need Lodash or Underscore, because this is just a map() operation, but you can use the _.map() function from those libraries if you like. 正如其他人所说,您不需要Lodash或Underscore,因为这只是map()操作,但是您可以根据需要使用这些库中的_.map()函数。

 var objs = [{ n_vId: 1, s_vName: 'test', d_date: '2016-03-15 00:00:00', f_a: 0, f_b: 0, f_c: 0, f_d: 4, f_e: 0, f_f: 0.1, f_g: 0 }, { n_vId: 2, s_vName: 'test', d_date: '2016-03-15 00:15:00', f_a: 1, f_b: 1, f_c: 0, f_d: 4, f_e: 0, f_f: 0.1, f_g: 0 }]; function transform(letter) { return _.map(objs, function (obj) { var out = { date: obj.d_date }; out[letter] = obj['f_' + letter]; return out; }); } var a = transform('a'), b = transform('b'); // etc. document.getElementById('out').textContent = JSON.stringify({a: a, b: b}, true, '\\t'); 
 <script src="https://cdn.jsdelivr.net/lodash/4.6.1/lodash.min.js"></script> <pre id="out"></pre> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM