将所有对象复制到数组中的最简单方法

时间:2017-09-26 15:52:44

标签: javascript webpack vuejs2

我有大约250个json文件,我想复制到数组,我的项目基于vuejs和webpack

这是我的代码

import ch1 from 'assets/json/ar/ch1.json';
import ch2 from 'assets/json/ar/ch2.json';
....
....
import ch100 from 'assets/json/ar/ch100.json';
import ch101 from 'assets/json/ar/ch101.json';
import ch102 from 'assets/json/ar/ch102.json';
import ch103 from 'assets/json/ar/ch103.json';
import ch104 from 'assets/json/ar/ch104.json';
import ch105 from 'assets/json/ar/ch105.json';
import ch106 from 'assets/json/ar/ch106.json';
import ch107 from 'assets/json/ar/ch107.json';
import ch108 from 'assets/json/ar/ch108.json';
import ch109 from 'assets/json/ar/ch109.json';

.....
....
import ch250  from 'assets/json/ar/ch250.json';



var myalldata=  []
// i can  do this manually  as assigning to each index like below
// myalldata[1]=ch1 ;
// myalldata[2]=ch2 ; but its too lengthy code



//here i export all data as array
export default { 
  alldata:myalldata
}

我可以使用for循环将所有对象复制到myalldata吗?该怎么做

2 个答案:

答案 0 :(得分:1)

根据this,您可以这样做:

let myalldata = [];
for (let i = 1; i < 251; i++)
  myalldata[i] = require("assets/json/ar/ch" + i + ".json");

注意:对于低于v2.0.0的版本,您将需要: https://github.com/webpack-contrib/json-loader

答案 1 :(得分:0)

如果你从同一个模块中导出它们,你可以这样做:

//从同一模块中导出所有 - exportCh.js

export ch1 from './path/ch1'
export ch2 from './path/ch2'
/// etc

然后导入它们:

这假设您可以使用ES8。

import * as myDataSets from './exportCh'
const myalldata = Object.values(myDataSets)

如果你能支持ES6:

import * as myDataSets from './exportCh'
const myalldata = Object.keys(myDataSets).reduce((a, d) => a.concat(myDataSets[d]), [])