不同对象之间递归并唯一组合,不重复

Recursion between different objects and combine them uniquely, without duplicate

我一直在尝试弄清楚如何对具有相似属性但也有差异的 2 个对象进行递归。我需要以独特的方式合并这两个对象,因此没有重复的国家或模型等。

编辑:请仅使用 vanilla js

var us1 = {
  country: {
    "United States": {
      "Ford": {
        "engine": {
          type1: "4 cyl",
          type2: "6 cyl"
        }
      },
      "Chevy": {
        "engine": {
          type1: "6 cyl"
        }
      }
    }
  }
}

var us2 = {
  country: {
    "United States": {
      "Ford": {
        "engine": {
          type3: "12 cyl"
        }
      },
      "Saturn": {
        "engine": {
          type1: "4 cyl"
        }
      }
    }
  }
}

var cars = [us1, us2];
var newCars = [];

function fn(cars) {
  if (typeof cars == "object") {
    for (var attr in cars) {
      if (!newCars.hasOwnProperty(cars[attr])) {
        newCars.push(cars[attr]);
      }

      fn(cars[attr])
    }
  } else {
    //
  }
}

console.log(fn(cars));
console.log(newCars)

想要的结果: var us1 = { country: { "United States": { "Ford": { "engine": { type1: "4 cyl", type2: "6 cyl", type2: "12 cyl" } }, "Chevy": { "engine": { type1: "6 cyl" } }, "Saturn": { "engine": { type1: "4 cyl" } } } } }

如果您愿意使用 underscore.js,以下应该有效:

_.extend(us1, us2)

使用lodash:

_.merge(us1, us2)

如果不想用库,自己写也很简单。类似于

// (to: Object, ...sources: Object[]) => Object
function mergeDeep(to) {
  const sources = Array.from(arguments).slice(1)

  // (to: Object, from: Object) => void
  const _merge = (to, from) => {
    for (let a in from) {
      if (a in to) {
        _merge(to[a], from[a])
      } else {
        to[a] = from[a]
      }
    }
  }

  sources.forEach(from => {
    _merge(to, from)
  })

  return to
}

在此处查看演示 https://tonicdev.com/bcherny/mergedeep

但实际上,您应该为此使用一个库。与任何广泛使用的现有实现相比,您自己编写它肯定会出现错误并且速度较慢。