JavaScript常用函数方法归纳

128 阅读1分钟

介绍

  • 求2个数组的交集并集差集

前置知识:采用new Setincludes以及filter

const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];

// 求交集
const intersection = [...new Set(arr1.filter(item => arr2.includes(item)))];
console.log(intersection); // [3, 4]

// 求并集
const union = [...new Set([...arr1, ...arr2])];
console.log(union); // [1, 2, 3, 4, 5, 6]

// 求差集
const difference = [...new Set(
  [...arr1.filter(item => !arr2.includes(item)), ...arr2.filter(item => !arr1.includes(item))]
)];
console.log(difference); // [1, 2, 5, 6]

// 数组去重
const arrUnique = [...new Set([...arr1, ...arr2])];
console.log(arrUnique); // [1, 2, 3, 4, 5, 6]

  • 对象数组去重
var arrList = [
      { id: 1 },
      { id: 2 },
      { id: 3 },
      { id: 4 },
      { id: 3 },
      { id: 2 },
    ]
    function removeDuplicates(arr) {
      let uniqueArr = [];
      let obj = {};

      for (let i = 0; i < arr.length; i++) {
        if (!obj[arr[i].id]) {
          uniqueArr.push(arr[i]);
          obj[arr[i].id] = true;
        }
      }

      return uniqueArr;
    }

    console.log(removeDuplicates(arrList));
  • 对象数组排序
const items = [
      { name: 'item1', rank: 3 },
      { name: 'item2', rank: 1 },
      { name: 'item3', rank: 2 },
    ];
    items.sort(function (a, b) {
      return a.rank - b.rank;
    });

    console.log(items);
  • 更换对象的key的名称
const data = [
      {
        id: 1,
        name: 'John',
        children: [
          {
            id: 2,
            name: 'Bob',
            children: [
              {
                id: 3,
                name: 'Alice',
                children: []
              }
            ]
          }
        ]
      },
      {
        id: 4,
        name: 'Mike',
        children: []
      }
    ];
    function renameFields(data, mapping) {
      return data.map(item => {
        const newItem = {};
        Object.keys(item).forEach(key => {
          if (key in mapping) {
            newItem[mapping[key]] = item[key];
          } else {
            newItem[key] = item[key];
          }
        });
        if (item.children && item.children.length > 0) {
          newItem.children = renameFields(item.children, mapping);
        }
        return newItem;
      });
    }

    const mapping = {
      id: 'value',
      name: 'label'
    };

    const newData = renameFields(data, mapping);
    console.log(newData);
  • 对象赋值
var aa = {
      id: null,
      name: undefined,
      age: 19
    }
    var bb = {
      id: 23,
      name: "张飒",
      age: 56,
      six: "男",
      bbbb: "dsds"
    }

    /**
   * @description 将来源对象的值赋值到目标对象里面,并返回赋值后的对象
   * @param {object} 目标对象  { name: undefined, age: 19 }
   * @param {object} 来源对象 { id: 23, name: "张飒",age: 56, six: "男" }
   * @returns 赋值后的对象  { name: "张飒", age: 56 }
   * 
   */
    function mergeObjects(obj1, obj2) {
      var newObj = {};
      for (var prop in obj1) {
        newObj[prop] = obj1[prop];
      }
      for (var prop in obj2) {
        if ([prop] in newObj) {
          newObj[prop] = obj2[prop];
        }
      }
      return newObj;
    }

    console.log(mergeObjects(aa, bb));
  • 对象数组根据某个字段去重
export const removeDuplicates = (arr, key) => {
  let uniqueArr = [];
  let obj = {};

  for (let i = 0; i < arr.length; i++) {
    if (!obj[arr[i][key]]) {
      uniqueArr.push(arr[i]);
      obj[arr[i][key]] = true;
    }
  }

  return uniqueArr;
}
  • 去除对象的空值
const SPACE_CHARS = ["", " ", "null", "undefined", null, undefined];

const replacer = (key, value) => {
  if (SPACE_CHARS.includes(value)) {
    return undefined;
  }
  if (/^ [\s]*$/.test(value)) {
    return undefined;
  }
  if (typeof value === "string") {
    return value.trim();
  }
  return value;
};

export const clearEmpty = (params) => {
  // Object.prototype.toString.call(params).slice(8,-1) === 'Object'
  let newObject = JSON.parse(JSON.stringify(params, replacer));
  return newObject;
}
  • 删除数组中空的children集合
export const deleteEmptyChildren = (data = []) => {
  for (let i = 0, l = data.length; i < l; i++) {
    const cur = data[i];
    const children = cur.children;
    if (children && children.length === 0) {
      delete cur.children;
      // delete cur.meta.icon;
      // delete cur.meta.rank;
    } else {
      deleteEmptyChildren(cur.children || []);
    }
  }

  return data;
}
  • 根据某个字段对对象数组进行排序
export const abilitySortByKey = (arr, property) => {
  let map = {};
  for (let i = 0; i < arr.length; i++) {
    const ai = arr[i];
    if (!map[ai[property]]) map[ai[property]] = [ai];
    else map[ai[property]].push(ai);
  }
  let res = [];
  Object.keys(map).forEach((key) => {
    res.push({
      // [property]: key,
      children: map[key],
      isRoot: true,
      QualificationTypeName: map[key][0].QualificationTypeName,
      ClinicalQualificationId: `root${map[key][0].ClinicalQualificationId}`,
      childrenLen: map[key].length
      // ...map[key][0]
    });
  });
  console.log(res
  );
  return res;
}