创建JSON的foreach ARRAY值线

问题描述 投票:0回答:2

嗨我试图用车把模板为此,我需要创建一个数组值的JSON

{"path":"Avions", "fileName":"AvionsEdit.vue"},{"path":"Avions", 
"fileName":"AvionsShow.vue"}ect...

我可以在代码的部分返回一个JSON等,但是我想是这样

{"path":["Avions","Avions"],"fileName": 
["AvionsEdit.vue","AvionsShow.vue"]}

var foo = {"path" : [], "fileName": []};
for(i = 0; i < list.length; i++) {
   foo.path.push(list[i]);
   foo.fileName.push(list[i]+extList[i]+".vue");
}
console.log(JSON.stringify(foo));

这里是我的名单

['Avions',
'Avions']

这里是我extList

['Edit',
'Show']
javascript json
2个回答
0
投票

觉得自己有点老派,使用所有这些嵌套的for循环,但我无法弥补别的(高度依赖于源数据的一致性,虽然非常简单,可读):

var srcData = {
  "path": [
    "somepath",
    "anotherpath",
    "yetanotherpath"
  ],
  "filename": [
    "somefilename",
    "anotherfile",
    "yetanotherfile"
  ]
};

const transform = src => {
   let res = [];
   let attributes = Object.keys(src);
   for(let i = 0; i < Object.values(src)[0].length; i++){
      let entry = {};
      for(let j = 0; j < attributes.length; j++){
          entry[attributes[j]] = Object.values(src)[j][i];
      }
      res.push(entry);
   }
   return res;
};

console.log(transform(srcData));

0
投票

我没有看到你的新的意见,我在等待一些通知,但它永远不会到来。我已经创建,生成所期望的输出的功能。这些不同的参数是:

  • 路径:路径或前缀列表
  • 文件:文件名
  • 后缀:后缀/扩展您的文件

var path = [ // path or prefix
      "path",
      "otherPath",
      "finalPath"
    ];
    var files = [ // file

      "Edit",
      "Get",
      "Foo"

    ];
console.log(transform(path,files,".vue")); 


 function transform(path, files,suffix) { // take your path, file and the suffix of your file
      if (path.length == files.length) { // check if the length is the same
        let results = { "path": [], "filename": [] }; // generate an object for the return
        for (let i = 0; i < path.length; i++) {
          results.path.push(path[i]); // push in the path array 
          results.filename.push(path[i]+files[i]+suffix) // push in the file name array. Concatenate the Path + File + the suffix

        }
        return results;
      }
    }
© www.soinside.com 2019 - 2024. All rights reserved.