从for循环的输出中创建一个js对象 [英] Create a js object from the output of a for loop

查看:269
本文介绍了从for循环的输出中创建一个js对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个js脚本来获取json文件的内容,
将html编码(通过node.js包)应用到对象值,然后将其吐出到json文件中



我想我有这个需要的开始和结束。
我可以从console.log看到,编码是成功地应用到每个对象的值,但我不知道如何从for循环的编码结果连贯地重新创建一个js对象。



我想了解一旦值被编码后,如何重新创建arr变量(如果这是正确的方法),那么我可以将其串化并输出一个json文件。

谢谢

  var arr = {
a :一些文本字符串,
b:要编码,
c:&转换回json文件,
d: 一旦他们被编码
};
for(var i = 0; i< arr.length; i ++){
var obj = arr [i];
(var key in obj){
var attrName = key;
var attrValue = obj [key];
var encodedAttrValue = encode(attrValue);

console.log(encodedAttrValue); //检查编码是否成功

var outputJson = //用编码的累积输出重新创建一个js对象,即每个encodedAttrValue


var outputFilename ='编码上传.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);
}
});



$解析方案

A简单的 Array.prototype.reduce with Object.assign 会做

  // objectMap可重用的实用程序
函数objectMap(f,a){
return Object.keys(a).reduce(function(b,k){
return Object.assign(b,{
[k]:f(a [k])
})
},{})
}

var arr = {
a:一些文本字符串,
b:待编码,
c:&转换返回一个json文件,
d:一旦它们被编码
}

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 (编码值已被保存到%s,outputFilename)
})

下面是一个代码片段,带有一个模拟的 encode 函数来显示中间的 encodedValues


$ b

//假装编码函数function encode(value){return value.toUpperCase()} // objectMap(f,a){return Object.keys(a).reduce(function(b,k){return Object.assign(b,{[k]:f(a [k])})} {})} var arr = {a:一些文本字符串,b:待编码,c:&转换回json文件,d:一旦他们编码} var encodedValues = objectMap(encode,arr)console.log(JSON.stringify(encodedValues,null,4))// {// a:某些字符串,//b:要编码,//c:&转换回JSON文件,//d:一旦它们被编码///


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

解决方案

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

这篇关于从for循环的输出中创建一个js对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆