Below is an example of ES6 code that converts one array format to another:
var data = [['A',10],['B',5],['C',15]];
var result = data.map( ([x, y]) => ({ x, y }) );
console.log(result);
Explanation
data.map()
: the map
function iterates through each element of the data
array (which has 3 elements) and executes the provided function for each element.
(...) => ....
: this syntax signifies an arrow function in ES6. It represents a concise way of defining functions with some differences from traditional function declarations.
[x, y]
: this is the destructuring assignment within the map
function. It assigns the individual elements of the inner arrays to variables x
and y
.
=>
: the arrow notation indicates the expression being returned by the function.
({ x, y })
: this is an object literal shorthand notation in ES6 which creates an object with properties x
and y
.
The map
method creates a new array by calling the function for each element and returning the results.
For comparison, here's the same code in ES5 syntax:
var data = [['A',10],['B',5],['C',15]];
result = data.map(function(arr) {
return { x: arr[0], y: arr[1] };
});
console.log(result);