Reputation: 1492
Very new to ES6. In ES5 I might do something like this
function newArray(){
var data = [];
for(var i = 0; i < 5; i++){
data[i] = "test data " + i;
}
return data;
}
x = newArray()
How would I do this in ES6 ? What I've got below is in error
getData = () => ({
let data = Array.from(new Array(5), (x, i) => "test data " + i)
return {
data
}
})
Upvotes: 2
Views: 2995
Reputation: 8542
In ES6 it should be something like this:
const data = Array.from(new Array(5), (x, i) => "test data " + i);
// if you want to return an object with the field data mapped to your array
const getData2 = () => ({ data });
console.log(getData2());
Upvotes: 1
Reputation: 48357
You create wrong the function with ES6
getData = () =>{
let data = Array.from(new Array(5), (x, i) => "test data " + i)
return {
data
};
}
console.log(getData())
You can fill an array
using fill
and map
methods.
//arr.fill(value, start, end)
getData = () =>{
let data = new Array(5).fill(0).map((a,i)=>"test data " + i);
return {
data
};
}
console.log(getData())
Upvotes: 2