"use strict";

exports.__esModule = true;
exports.arrayGroupBy = void 0;

/**
 * 对数组进行分组，分组后的对象
 * @category 数组
 * @function arrayGroupBy
 * @returns  {object} {"fieldName":[{...}],...}
 * @static
 * @author hht
 * @param {string}} key 分组属性.
 * @param {array} data 数组数据。
 *
 * @example example 01 匹配子节点
 * --------------------------------------------------------------------------
 * import { arrayGroupBy } from "@riil-frontend/utils";
 * const array =  [
 *  {
 *    type: 'assets',
 *    name: 'zhangsan',
 *    age: '33',
 *  },
 *  {
 *    type: 'config',
 *    name: 'a',
 *    age: '13',
 *  },
 *  {
 *    type: 'run',
 *    name: 'lisi',
 *    age: '3',
 *  },
 *  {
 *    type: 'xx',
 *    name: 'timo',
 *    age: '4',
 *  },
 *];
 * arrayGroupBy(array,'type',);
 *
 * result:{
 *    assets: [{ age: '33', name: 'zhangsan', type: 'assets' }],
 *    config: [{ age: '13', name: 'a', type: 'config' }],
 *    run: [{ age: '3', name: 'lisi', type: 'run' }],
 *    xx: [{ age: '4', name: 'timo', type: 'xx' }],
 *  };
 *
 * @example example 02 null
 * --------------------------------------------------------------------------
 * const array = null;
 * arrayGroupBy(array,"type");
 *
 * result:{}
 *
 * @example example 03 key undefind
 * --------------------------------------------------------------------------
 * const array =  [
 *  {
 *    type: 'assets',
 *    name: 'zhangsan',
 *    age: '33',
 *  },
 *  {
 *    type: 'config',
 *    name: 'a',
 *    age: '13',
 *  },
 *  {
 *    type: 'run',
 *    name: 'lisi',
 *    age: '3',
 *  },
 *  {
 *    type: 'xx',
 *    name: 'timo',
 *    age: '4',
 *  },
 *];
 * arrayGroupBy(array,"xx");
 *
 * {}
 *
 */
var arrayGroupBy = function arrayGroupBy(data, key) {
  if (!Array.isArray(data)) return {};
  var groupObj = {};
  data.forEach(function (item) {
    if (!item[key]) return;
    var fieldName = item[key];

    if (!groupObj[fieldName]) {
      groupObj[fieldName] = [item];
      return;
    }

    groupObj[fieldName].push(item);
  });
  return groupObj;
};

exports.arrayGroupBy = arrayGroupBy;