simplest method for Copying all objects into array

2019-07-13 20:53发布

I have around 250 json files which i want to copy to an array, my project is based on vuejs and webpack

here is my code below

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
}

can i use for loop for copying all objects to myalldata?? how to do that

2条回答
劫难
2楼-- · 2019-07-13 21:18

if you export them all from the same module you could do something like this:

// exports all from the same module - exportCh.js

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

Then import them:

This is assuming you're able to use ES8.

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

If you can support up to ES6:

import * as myDataSets from './exportCh'
const myalldata = Object.keys(myDataSets).reduce((a, d) => a.concat(myDataSets[d]), [])
查看更多
在下西门庆
3楼-- · 2019-07-13 21:19

According to this, you could do:

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

Note: for versions below v2.0.0, you will need this: https://github.com/webpack-contrib/json-loader

查看更多
登录 后发表回答