fivedoor fivedoor - 5 months ago 12
JSON Question

Create a js object from the output of a for loop

I'm trying to write a js script that takes the contents of a json file and
applies html encoding (via a node.js package) to the object values and then spits it back out into a json file

I think I have the start and end of what I need to do it.
I can see from console.log that the encoding is being applied successfully to each object value but I'm not sure how to coherently recreate a js object from the encoded results of the for loop.

I want to understand how I can recreate the arr variable once the values are encoded (if that is the right way to go about it) so I can then stringify and output a json file.

Thanks

var arr = {
"a": "Some strings of text",
"b": "to be encoded",
"c": "& converted back to a json file",
"d": "once they're encoded"
};
for(var i=0;i<arr.length;i++){
var obj = arr[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
var encodedAttrValue = encode(attrValue);

console.log(encodedAttrValue); // checking encoding is successful

var outputJson = // recreate a js object with the cumulated output of the encoding i.e. each encodedAttrValue


var outputFilename = 'encoded.json';
fs.writeFile(outputFilename, JSON.stringify(outputJson, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("Encoded version has been saved to " + outputFilename);
}
});
}
}

Answer

A simple Array.prototype.reduce with Object.assign will do

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,k) {
  return Object.assign(out, {[k]: encode(arr[k])})
}, {})

fs.writeFile(outputFilename, JSON.stringify(encodedValues, null, 4), function(err) {
  if (err)
    console.error(err.message)
  else
    console.log("Encoded values have been saved to %s", outputFilename)
})

Here's a code snippet with a mocked encode function to show you the intermediate encodedValues

// pretend encode function
function encode(value) {
  return value.toUpperCase()
}

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,k) {
  return Object.assign(out, {[k]: encode(arr[k])})
}, {});

console.log(JSON.stringify(encodedValues, null, 4))

// {
//    "a": "SOME STRINGS OF TEXT",
//    "b": "TO BE ENCODED",
//    "c": "& CONVERTED BACK TO A JSON FILE",
//    "d": "ONCE THEY'RE ENCODED"
// }