JS对象合并指南

发布时间:2023-05-19

一、js对象合并方法

js对象合并是指将多个对象合并成一个对象。其中一个对象是基础对象,其他对象的属性会被合并到该基础对象中。下面是一个基础的js对象合并方法:

/**
 * 合并一个或多个对象到第一个对象
 * @param target  目标对象,最终被修改的对象
 * @param source  要合并的对象
 * @returns {*}
 */
function extend(target, source) {
  for (let key in source) {
    if (source.hasOwnProperty(key)) {
      target[key] = source[key];
    }
  }
  return target;
}

以上代码展示了一个简单的对象合并方法,遍历传入的所有对象,将其属性添加到目标对象中。如果属性名称相同,则会覆盖目标对象的属性。 可以将该方法用于合并任意数量的对象。

二、js对象合并并去重

在前面提到的js对象合并方法中,如果属性名称相同,会覆盖目标对象的属性。如果希望保留重复的属性,则需要在合并时进行去重。下面是一个带有去重功能的js对象合并方法:

/**
 * 合并一个或多个对象到第一个对象并去重
 * @param target  目标对象,最终被修改的对象
 * @param sources  要合并的对象
 * @returns {*}
 */
function merge(target, ...sources) {
  sources.forEach(function (source) {
    for (let key in source) {
      if (source.hasOwnProperty(key)) {
        if (!target.hasOwnProperty(key)) {
          target[key] = source[key];
        } else if (Array.isArray(target[key]) && Array.isArray(source[key])) {
          target[key] = [...new Set([...target[key], ...source[key]])];
        } else if (typeof target[key] === 'object' && typeof source[key] === 'object') {
          merge(target[key], source[key]);
        } else {
          target[key] = source[key];
        }
      }
    }
  });
  return target;
}

该方法除了遍历要合并的对象外,还增加了一个去重的功能。对于重复的属性,如果是两个数组,则进行并集去重;如果是两个对象,则进行递归遍历。

三、js两个对象合并成一个数组

除了将多个对象合并成一个对象外,有时也需要将两个对象合并成一个数组。下面是一个将两个对象合并成一个数组的js方法:

/**
 * 两个对象合并成一个数组
 * @param a  对象A
 * @param b  对象B
 * @returns {Array} 合并后的数组
 */
function mergeToArray(a, b) {
  let arr = [];
  for (let key in a) {
    if (a.hasOwnProperty(key)) {
      arr.push(a[key]);
    }
  }
  for (let key in b) {
    if (b.hasOwnProperty(key)) {
      arr.push(b[key]);
    }
  }
  return arr;
}

该方法简单直接,将两个对象的所有属性值放入一个数组中返回。

四、js对象合并指定属性

有时候只需要合并指定的属性,而不是所有属性。下面是一个合并指定属性的js对象合并方法:

/**
 * 合并指定属性到目标对象中
 * @param target 目标对象
 * @param source 来源对象
 * @param keys 合并的属性
 */
function mergeKeys(target, source, keys) {
  keys.forEach(function (key) {
    if (source.hasOwnProperty(key)) {
      target[key] = source[key];
    }
  });
}

上述代码中,只有指定的属性会被合并到目标对象中。

五、js深度合并对象

有时候需要同时合并对象中嵌套的对象,实现深度合并,下面是一个深度合并对象的方法:

/**
 * 深度合并对象
 * @param target 目标对象
 * @param source 来源对象
 * @returns {*}
 */
function mergeDeep(target, source) {
  const isObject = (obj) => typeof obj === 'object' && obj !== null;
  if (!isObject(target) || !isObject(source)) {
    return source;
  }
  for (let key in source) {
    if (source.hasOwnProperty(key)) {
      const targetValue = target[key];
      const sourceValue = source[key];
      if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
        target[key] = [...targetValue, ...sourceValue];
      } else if (isObject(targetValue) && isObject(sourceValue)) {
        target[key] = mergeDeep({...targetValue}, sourceValue);
      } else {
        target[key] = sourceValue;
      }
    }
  }
  return target;
}

该方法会进行递归遍历,合并所有嵌套的对象。

六、js对象合并并返回新的对象

上面的大多数方法都是在原有对象上进行合并,如果需要返回一个新对象,可以使用以下方法:

/**
 * 新对象合并
 * @param sources 要合并的对象
 * @returns {*|{}} 合并后的新对象
 */
function mergeNew(...sources) {
  return sources.reduce(function (acc, obj) {
    return Object.assign(acc, obj);
  }, {});
}

该方法会将所有传入的对象合并为一个新的对象并返回。

七、js合并对象

除了上述方法外,还有其他方法可以合并对象。 例如,使用ES6语法可以通过以下方式合并对象:

let a = {a: 1, b: 2};
let b = {b: 3, c: 4};
let c = {...a, ...b}; // {a: 1, b: 3, c: 4}

使用lodash库可以通过以下方式合并对象:

const _ = require('lodash');
let a = {a: 1, b: 2};
let b = {b: 3, c: 4};
let c = _.merge({}, a, b); // {a: 1, b: 3, c: 4}

八、js对象合并成为一个对象

除了将多个对象合并成一个对象外,还有一种情况是将一组具有相同键的对象合并成一个对象。下面是一个将一组对象合并成一个对象的js方法:

let arr = [{name: "Tom", age: 20}, {name: "Jack", age: 25}];
let obj = arr.reduce((acc, cur) => {
  acc[cur.name] = cur.age;
  return acc;
}, {});
console.log(obj); // {Tom: 20, Jack: 25}

该方法通过迭代传入的数组,将具有相同键的对象合并为一个对象并返回。

九、对象合并的几种方法

以上介绍了常见的js对象合并方法,除此之外还有其他一些方法。 使用jQuery库可以通过以下方式合并对象:

let a = {a: 1, b: 2};
let b = {b: 3, c: 4};
let c = $.extend({}, a, b); // {a: 1, b: 3, c: 4}

使用Object.assign方法可以将多个对象合并为一个对象:

let a = {a: 1, b: 2};
let b = {b: 3, c: 4};
let c = Object.assign({}, a, b); // {a: 1, b: 3, c: 4}

在ES8中可以使用对象展开符(...)来简单地合并对象:

let a = {a: 1, b: 2};
let b = {b: 3, c: 4};
let c = {...a, ...b}; // {a: 1, b: 3, c: 4}

综上所述,JS合并对象的方法众多,根据实际需求选择合适的方法能够更加高效地完成对象合并的任务。