从 for 循环的输出创建一个 js 对象

Create a js object from the output of a for loop

本文关键字:一个 js 对象 循环 for 输出 创建      更新时间:2023-09-26

我正在尝试编写一个 js 脚本,该脚本获取 json 文件的内容并 将HTML编码(通过节点.js包)应用于对象值,然后将其吐回json文件

我想我已经有了我需要做的事情的开始和结束。 我可以从控制台看到.log编码已成功应用于每个对象值,但我不确定如何从 for 循环的编码结果连贯地重新创建 js 对象。

我想了解如何在对值进行编码后重新创建 arr 变量(如果这是正确的方法),以便我可以字符串化并输出 json 文件。

谢谢

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

一个简单的Object.assign Array.prototype.reduce就可以了

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

下面是一个带有模拟encode函数的代码片段,用于向您展示中间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"
// }

您可以将其直接编写为:

newObj = {};
for (k in obj) { newObj[k] = encode(obj[k]); }

循环遍历 json 对象时使用 .push(obj) 方法。

首先将outputJson从循环中取出,然后在完成编码后将其推送到outputJson

outputJson.push({
  attrName: key,
  attrValue: encodedAttrValue
});

这应该可以解决问题。