不同对象之间的递归,并将它们唯一地组合在一起,不重复

Recursion between different objects and combine them uniquely, without duplicate

本文关键字:唯一 组合 在一起 对象 之间 递归      更新时间:2023-09-26

我一直在尝试如何对两个属性相似但也有差异的对象进行递归。我需要以一种独特的方式合并这两个对象,这样就没有重复的国家或型号等。

编辑:仅限香草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" } } } } }

如果您不想使用库,那么编写自己的代码是很琐碎的。类似的东西

// (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

但实际上,你应该使用一个库来实现这一点。与任何广泛使用的现有实现相比,自己编写它肯定会更麻烦、更慢。

使用lodash:

_.merge(us1, us2)

如果您对使用underscore.js持开放态度,那么以下操作应该有效:

_.extend(us1, us2)