JS Code block 代码块–对象(Object)

星期二, 2023-04-18 | Author: Lee | computer, 前端 | 496 views

对象(Object)
校验对象是否是某个类型
是否对象类型
是否数组类型
是否数组
是否是字符串
是否时blob
判断对象是否为空
class 类多继承
判断参数是不是blob
深层克隆对象
两个对象(值)之间的深入比较,以确定它们是否相等
过滤对象中为空的属性
反转对象的键值对
数组转换为键值对的对象
对象转化为键值对

/**
 * 校验对象是否是某个类型
 * @param obj 要校验的对象
 * @param type 类型
 * @returns {*|URL}
 */
function checkType(obj, type) {
    return Object.prototype.toString.call(obj).toLowerCase() === `[object ${type}]`;
}
 
/**
* 是否对象类型
* @param obj
* @return {*|URL}
*/
function isObject(obj) {
    return checkType(obj, 'object');
}
 
/**
* 是否数组类型
* @param arr
* @return {*|URL}
*/
function isArray(arr) {
    return checkType(arr, 'array');
}
 
/**
* 是否是函数
* @param fun
* @return {*|URL}
*/
function isFunction(fun) {
    return checkType(fun, 'function')
}
 
/**
 * 是否是字符串
 * @param {*} obj
 */
function isString(obj) {
    return checkType(obj, 'string')
}
 
/**
 * 是否时blob
 * @param {*} obj
 */
function isBlob(obj) {
    return checkType(obj, 'blob')
}
 
/**
 * 
 * @desc   判断对象是否为空
 * @param  {Object} obj
 * @return {Boolean}
 */
function isEmptyObject(obj) {
    if (!obj || typeof obj !== 'object' || Array.isArray(obj))
        return false
    return !Object.keys(obj).length
}
 
/**
* class 类多继承
* @param mixins
* @return {Mix}
*/
function mix(...mixins) {
    // 深拷贝
    function copyProperties(target, source) {
        for (let key of Reflect.ownKeys(source)) {
            if ( key !== 'constructor' && key !== 'prototype' && key !== 'name') {
                let desc = Object.getOwnPropertyDescriptor(source, key);
                Object.defineProperty(target, key, desc);
            }
        }
    }
    class Mix {
        constructor(...param) {
          for (let mixin of mixins) {
            copyProperties(this, new mixin(...param)); // 拷贝实例属性
          }
        }
    }
 
    for (let mixin of mixins) {
        copyProperties(Mix, mixin); // 拷贝静态属性
        copyProperties(Mix.prototype, mixin.prototype); // 拷贝原型属性
    }
    return Mix;
}
 
/**
 * 深层克隆对象
 * @param obj
 * @returns {*}
 * @example
 * const a = { foo: 'bar', obj: { a: 1, b: 2 } };
 * const b = deepClone(a);
 * // => a !== b, a.obj !== b.obj
 */
function deepClone(obj) {
  let clone = Object.assign({}, obj);
  Object.keys(clone).forEach(
    (key) => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
  );
  return Array.isArray(obj) && obj.length
    ? (clone.length = obj.length) && Array.from(clone)
    : Array.isArray(obj)
      ? Array.from(obj)
      : clone;
}
 
/**
 * 两个对象(值)之间的深入比较,以确定它们是否相等
 * @param {Object} a
 * @param {Object} b
 * @returns {*}
 * @example
 * equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' });
 * // => true
 */
function equals(a, b) {
  if (a === b) return true;
  if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
  if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
  if (a === null || a === undefined || b === null || b === undefined) return false;
  if (a.prototype !== b.prototype) return false;
  let keys = Object.keys(a);
  if (keys.length !== Object.keys(b).length) return false;
 
  return keys.every((k) => equals(a[k], b[k]));
}
 
/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 * @example
 * filterEmptyPropObj({name: 'foo', sex: ''})
 * // => {name: 'foo'}
 */
function filterEmptyPropObj(obj) {
  if (!(typeof obj == 'object')) return;
 
  for (let key in obj) {
    if (obj.hasOwnProperty(key)
      && (obj[key] == null || obj[key] == undefined || obj[key] === '')) {
      delete obj[key];
    }
  }
  return obj;
}
 
/**
 * 反转对象的键值对
 * 而不会改变它。使用 Object.keys() 和 Array.reduce() 来反转对象的键值对。
 * @param obj
 * @returns {{}}
 * @example
 * invertKeyValues({ name: 'John', age: 20 });
 * // => { 20: 'age', John: 'name' }
 */
function invertKeyValues (obj) {
    Object.keys(obj).reduce((acc, key) => {
        acc[obj[key]] = key;
        return acc;
    }, {});
}
 
/**
 * 数组转换为键值对的对象
 * @since 1.2.1
 * @param array
 * @returns {*}
 * @example
 * objectFromPairs([['a',1],['b',2]]);
 * // => {a: 1, b: 2}
 */
function objectFromPairs(array) {
  return Array.isArray(array) && array.reduce((a, v) => (a[v[0]] = v[1], a), {});
}
 
/**
 * 对象转化为键值对
 * 使用 Object.keys() 和 Array.map() 遍历对象的键并生成一个包含键值对的数组。
 * @param obj
 * @returns {any[][]}
 * @example
 * objectToPairs({ a: 1, b: 2 });
 * // => [['a',1],['b',2]]
 */
function objectToPairs (obj) {
    return Object.keys(obj).map((k) => [k, obj[k]]);
}

Tags:

文章作者: Lee

本文地址: https://www.pomelolee.com/2389.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta