-1

Let's say I have the following Object.

 const result = [{date:'2016-11-21',name:'Bob',score:0.1034947}{date:'2016-10-21',name:'Bill',score:0.2081911},{date:'2016-10-21',name:'Mary',score:0.234947},{date:'2016-10-21',name:'Bob',score:0.1034947},{date:'2016-11-21',name:'Bill',score:0.2081911},{date:'2016-11-21',name:'Mary',score:0.234947},{date:'2016-12-21',name:'Bob',score:0.1034947},{date:'2016-12-21',name:'Bill',score:0.2081911},{date:'2016-12-21',name:'Mary',score:0.234947}];

What I want to take that object and turn those values and put them in separate arrays. So for example,

dateArray = ['2016-11-21','2016-10-21', ....]

I am really quite new to JavaScript. I am trying to do it with map but not sure if I am on the right track. So thanks in advance!

Kulwant
  • 641
  • 2
  • 11
  • 28

2 Answers2

1
var dateArray = [];

for (var index in result) {
    var item = result[index];
    dateArray.push(item.date);
}
tehabstract
  • 529
  • 6
  • 14
-1

You can use Array.prototype.map to transform your array to a new one by projecting every original value with the defined function.

var dateArray = result.map(function(r) { 
    return r.date;
});

This code literally means "take array result and make a new array dateArray of the same length where every item is a value of date property of corresponding item of result".

You can also use arrow-function, but it is only compatible with ECMAScript 6.

var dateArray = result.map(r => r.date);
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101