SOLVED: My object value assignment should have been a[1] not obj[1]
I'm practising some functional programming with javascript and I don't yet fully understand using the arrow function so I am trying to steer away from using. This is the solution to my problem set but I need help writing it in a way that I understand.
function transformEmployeeData(array){
return array.map(a =>{
var obj = {};
a.forEach(a => obj[a[0]] = a[1]);
return obj;
});
This is how i rewrote the function but it doesn't compile. Can anyone help me understand my shortcomings on this ?
function transformEmployeeData(array) {
return array.map(function(x) {
var obj = {};
x.forEach(function(a){
obj[a[0]] = obj[1];
return obj;
});
});
}
It's easy to omit both arrow functions and anonymous function by making them named functions. Here is my suggestion:
function transformEmployeeData(arrayOfArray) {
function transform(arr) {
const map = {};
function registerMap (arr) {
map[arr[0]] = arr[1];
}
arr.forEach(registerMap);
return obj;
}
return arrayOfArray.map(transform);
};
We can rewrite the named functions to using binding to a function expression:
const transformEmployeeData = function(arrayOfArray) {
const transform = function (arr) {
const map = {};
const registerMap = function (arr) {
map[arr[0]] = arr[1];
}
arr.forEach(registerMap);
return obj;
}
return arrayOfArray.map(transform);
};
And then we can rewrite this back to arrow functions:
const transformEmployeeData = (arrayOfArray) => {
const transform = (arr) => {
const map = {};
const registerMap = (arr) => {
map[arr[0]] = arr[1];
}
arr.forEach(registerMap);
return obj;
}
return arrayOfArray.map(transform);
};
Then we can replace the variable with it's definition:
const transformEmployeeData = (arrayOfArray) => {
return arrayOfArray.map((arr) => {
const map = {};
arr.forEach((arr) => {
map[arr[0]] = arr[1];
});
return obj;
});
};
When there is only one argument then the parentheses are optional. If the body is one expression you can omit the curlies. Thus we can remove optional syntax:
const transformEmployeeData = arrayOfArray =>
arrayOfArray.map(arr => {
const map = {};
arr.forEach(arr => {
map[arr[0]] = arr[1];
});
return obj;
});
Coding styles like airbnb suggests we don't remove parenses if we have curlies, thus:
const transformEmployeeData = arrayOfArray =>
arrayOfArray.map((arr) => {
const map = {};
arr.forEach((arr) => {
map[arr[0]] = arr[1];
});
return obj;
});
Arrow functions don't bind this
so these are equal just because we are not using this
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.