[Solved] Create a js object from the output of a for loop


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

// objectMap reusable utility
function objectMap(f,a) {
  return Object.keys(a).reduce(function(b,k) {
    return Object.assign(b, {
      [k]: f(a[k])
    })
  }, {})
}

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

// objectMap reusable utility
function objectMap(f,a) {
  return Object.keys(a).reduce(function(b,k) {
    return Object.assign(b, {
      [k]: f(a[k])
    })
  }, {})
}

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 = objectMap(encode, arr)

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"
// }

3

solved Create a js object from the output of a for loop