2

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
    }
})
3
  • What is the error ? Commented Apr 18, 2017 at 10:25
  • unexpected token ^ let data. It's my ES6 syntax that in error. not sure what to do Commented Apr 18, 2017 at 10:27
  • 1
    the issue is the outer () after the => ... surrounding {} with () makes {} an object literal, which means you have an invalid syntax for an object literal Commented Apr 18, 2017 at 10:29

2 Answers 2

2

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())

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

1 Comment

@Rory, don't forget to accept one answer in order to help other people.
1

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());

1 Comment

OP seems to want getData to return an object... not sure why.

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.