0

How can I turn this array:

var users = [
  {
    'date':'jan',
    'visits': 2,
    'drops': 1
  },
  {
    'date':'feb',
    'visits': 3,
    'drops': 2
  }
]

into this array:

var newArray = [
  {
    'name': 'visits',
    'data': [
      2, 3
    ]
  },
  {
    'name': 'drops',
    'data': [
      1, 2
    ]
  }
]

using

newArray = users.map(function(){
  return ...
});

Thanks!

1
  • 1
    You don't want map for this, as users.length and newArray.length are unrelated. You might want forEach instead, and simply add to two objects from there. Commented Feb 22, 2016 at 17:43

3 Answers 3

1

You can reduce it like this:

var result = users.reduce(function(r, i) {
    r[0].data.push(i.visits);
    r[1].data.push(i.drops);
    return r;
}, [
    { name: 'visits', data: [] },
    { name: 'drops', data: [] }
]);
Sign up to request clarification or add additional context in comments.

Comments

0

Just a more versatile solution.

var users = [{ 'date': 'jan', 'visits': 2, 'drops': 1 }, { 'date': 'feb', 'visits': 3, 'drops': 2 }],
    result = function (data, names) {
        var r = [];
        data.forEach(function (a) {
            names.forEach(function (b, i) {
                r[i] = r[i] || { name: b, data: [] };
                r[i].data.push(a[b])
            });
        });
        return r;
    }(users, ['visits', 'drops']);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Comments

0

You can transform your array using a reduction function. This is dynamic.

var users = [{
  'date': 'jan',
  'visits': 2,
  'drops': 1
}, {
  'date': 'feb',
  'visits': 3,
  'drops': 2
}];

function transform(data, blacklist) {
  return Object.keys(data[0]).filter(function(key) {
    return blacklist.indexOf(key) === -1;
  }).map(function(key) {
    return data.reduce(function(obj, record) {
      obj.data.push(record[key]);
      return obj;
    }, {
      name: key,
      data: []
    });
  });
}

function print(obj) {
  document.body.innerHTML = '<pre>' + JSON.stringify(obj, null, 2) + '</pre>';
}

print(transform(users, ['date']));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.