0

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.

0

3 Answers 3

2

You can simply use 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't even need a library for this one
1

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.

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>

1 Comment

Thumbs up for the transform function: I was going to add the transform function to my answer too, but decided to keep it simple.
1

Take a look at this npm module 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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.