如何使用JavaScript重新映射数组

时间:2018-08-16 12:43:45

标签: javascript arrays

如何从中重新映射此示例数组

const webpack = require('webpack');
const helpers = require('./helpers');
const path = require('path');
const ngcPlugin = require('ngc-webpack');
const CopyWebpackPlugin = require("copy-webpack-plugin");
const EntriesPlugin = require('webpack-entries');
const autoprefixer = require('autoprefixer');
const AOT = true;
const PurifyPlugin = require('@angular-devkit/build-optimizer').PurifyPlugin;

const ENV = process.env.NODE_ENV = process.env.ENV = 'production';

module.exports = {
  devtool: 'source-map',

  context: helpers.root('src'),

  entry: EntriesPlugin(helpers.root('src/**/!(*.spec).ts'), true),

  resolve: {
    extensions: ['.js', '.ts']
  },

  output: {
    path: helpers.root('lib'),
    publicPath: './[path]',
    filename: '[name].js',
    libraryTarget: 'commonjs2'
  },

  stats: {
    assets: false,
    children: false,
    chunks: false,
    maxModules: 0
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        enforce: 'pre',
        loader: 'tslint-loader',
        options: {
          formatter: 'stylish',
          emitErrors: true,
          failOnHint: false,
          typeCheck: false
        }
      },
      {
        test: /\.ts$/,
        loaders: ['@angular-devkit/build-optimizer/webpack-loader',  '@ngtools/webpack'],
        exclude: helpers.root('index.ts')
      },
      {
        test: /\.html$/,
        loaders: 'raw-loader'
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file-loader?name=assets/[name].[ext]'
      },
      {
        test: /\.(scss|css)$/,
        loaders: [
          "raw-loader",
          "postcss-loader",
          "sass-loader"
        ]
      }
    ]
  },

  externals: (context, request, callback) => {
    // modules that are not absolute path or relative path are externals
    // 'src/index.ts' is the only module referenced by absolute path

    const isItemExcludable = !path.isAbsolute(request) && /^[@a-zA-Z0-9\-]/.test(request);
    if (isItemExcludable) {
      return callback(null, request);
    }

    callback();
  },

  plugins: [
    new ngcPlugin.NgcWebpackPlugin({
      AOT,
      tsConfigPath: './tsconfig.lib.json'
    }),
    new PurifyPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new CopyWebpackPlugin([
      {
        from: helpers.root('src/**/*.scss'),
        to: helpers.root('lib/[path]/[name].[ext]')
      },
      {
        from: helpers.root('src/**/*component.html'),
        to: helpers.root('lib/[path]/[name].[ext]')
      }
    ]),
    new webpack.optimize.UglifyJsPlugin({
      mangle: {
        keep_fnames: true
      },
      compress: {
        warnings: false
      }
    }),
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(ENV)
      }
    }),
    new webpack.LoaderOptionsPlugin({
      options: {
        context: helpers.root('src'),
        sassLoader: {
          includePaths: [helpers.root('src', 'scss')]
        },
        postcss: [autoprefixer({browsers: ['last 1 version']})],
      }
    })
  ]
};

此数组:

var keyData = [
  { 'dir': 'left', 'code': 93 },
  { 'dir': 'left', 'code': 971 },
  { 'dir': 'right', 'code': 975 },
  { 'dir': 'right', 'code': 976 },
];

我可以使用lodash解决此数组吗?

5 个答案:

答案 0 :(得分:2)

如果您只想拥有一个顶层对象,而不是一个数组:

keyData = {
   left: keyData.filter(function(o) { return o.dir === 'left'; }),
   right: keyData.filter(function(o) { return o.dir === 'right'; })
};

如果您只想拥有一个包含对象的顶级数组,则:

keyData = [{
   left: keyData.filter(function(o) { return o.dir === 'left'; }),
   right: keyData.filter(function(o) { return o.dir === 'right'; })
}];

答案 1 :(得分:1)

您可以使用Arrays中的reduce函数来构造新对象

var keyData = [
  { 'dir': 'left', 'code': 93 },
  { 'dir': 'left', 'code': 971 },
  { 'dir': 'right', 'code': 975 },
  { 'dir': 'right', 'code': 976 },
];

keyData.reduce((prev, curr)=>{
  if(curr.dir==="right"){
    prev.right.push(curr)
  }else{
    prev.left.push(curr)
   }
  return prev
},{left:[], right:[]})

答案 2 :(得分:1)

这是最有效的方式:

var keyData = [
  { 'dir': 'left', 'code': 93 },
  { 'dir': 'left', 'code': 971 },
  { 'dir': 'right', 'code': 975 },
  { 'dir': 'right', 'code': 976 },
];

var result = {}

for (let obj of keyData) {
  result[obj.dir] = result[obj.dir] || []
  result[obj.dir].push(obj)
}

console.log(result)

答案 3 :(得分:1)

  

loadash 中使用groupBy

您可以使用loadash的groupBy方法,如下所示:

<select id="mySelect">...</select>
<td id="myCell">...</td>
<script>
    document.getElementById('mySelect').addEventListener('change', function (event) {
        document.getElementById('myCell').className = event.target.value;
    });
</script>
var keyData = [
  { 'dir': 'left', 'code': 93 },
  { 'dir': 'left', 'code': 971 },
  { 'dir': 'right', 'code': 975 },
  { 'dir': 'right', 'code': 976 },
];
console.log(_.groupBy(keyData, (data) => data.dir));

答案 4 :(得分:1)

有效结果是对象,而不是数组:

{
  left: [
    { 'dir': 'left', 'code': 93 },
    { 'dir': 'left', 'code': 971 },
  ],
  right: [
    { 'dir': 'right', 'code': 975 },
    { 'dir': 'right', 'code': 976 },
  ]
};

ES2018实施

const remap = (arr) => arr.reduce((acc, el) => ({
  ...acc,
  [el.dir]: acc[el.dir] ? [...acc[el.dir], el] : [el]
}), {});

const data = [
  { 'dir': 'left', 'code': 93 },
  { 'dir': 'left', 'code': 971 },
  { 'dir': 'right', 'code': 975 },
  { 'dir': 'right', 'code': 976 }
];

console.log(remap(data));