After consulting the method/object definitions on MDN, I am attempting to create a simplified step-by-step explanation of how the script below (referenced from a previous post) is functioning. This will not only aid in my understanding but also help me adapt it further.
There are certain aspects that confuse me, so my explanation may seem a bit convoluted, but I'm hopeful that someone can clarify where I've gone astray or misunderstood...
(Note: The encode function is solely used to encode HTML and is required from a node.js package)
var arr = {
"a": "Some strings of text",
"b": "to be encoded",
"c": "& converted back to a json file",
"d": "once they're encoded"
}
var encodedValues = Object.keys(arr).reduce(function(out,key) {
return Object.assign(out, {[key]: endcode(arr[key])})
}, {});
console.log(encodedValues);
Explanation
Create a variable “encodedValues” which will:
1 Object.keys(arr)
loop over and return the object arr
’s properties in the order they are provided
2 .reduce(function(out,key)
First applying the following function to execute on each value in the array ("and reduce it to a single value" *):
3
return Object.assign(out, {[key]: endcode(arr[key])})
The function copies the values of all properties from the source object to a target object we will call “out”.
4 The source object has an encoding function {[key]: encode(arr[key])}
applied to it so that where key
is an object encode
is applied to its property
5 }, {});
I assume this part , {}
is the initialValue for .reduce i.e. the value used as the first argument to the first call of the callback, which starts as an empty object?
6
Object.keys
returns an array (of the given object arr
's encoded properties in the order they were provided)
7 which is then logged to the console
*I don't understand how or why we "reduce it to a single value" in this case?? Doesn't that suggest a concatination of the values is part of the process:
"Some strings of text" + "to be encoded" + "& converted back to a json file" + "once they're encoded"
. I don't really get how or why this is part of the working solution
Thanks!