多级对象-基于键的破坏性合并

时间:2019-04-04 11:23:26

标签: javascript object lodash javascript-objects

我有两个对象。基本上是模型和数据情况。无法弄清楚如何递归删除数据对象中已从模型中删除的项目。

首先是模型:

var foo = {
  "title": "Enter title",
  "info": {
    "released": "Enter year",
    "runtime": "Enter time"
  }
}

另一个是数据:

var bar = {
  "title": "Forrest Gump",
  "info": {
    "released": "1994",
    "runtime": "02:22",
    "awards": "3"
  }
  "genre": "Drama/Comedy-drama"
}

我正在尝试对两个对象进行通用比较,结果是:

var bar = {
  "title": "Forrest Gump",
  "info": {
    "released": "1994",
    "runtime": "02:22"
  }
}

任何帮助将不胜感激!

如果能够添加存在于蓝图中但不存在于数据中的对象键和值,则将是一个超级奖励。我有单独工作,但这将是一个不错的奖励!

2 个答案:

答案 0 :(得分:3)

Object.keys上的递归函数应该可以正常工作:

var foo = {
  "title": "Enter title",
  "info": {
    "released": "Enter year",
    "runtime": "Enter time"
  }
};

var bar = {
  "title": "Forrest Gump",
  "info": {
    "released": "1994",
    "runtime": "02:22",
    "awards": "3"
  },
  "genre": "Drama/Comedy-drama"
}

function getBoth(base, data) {
  var result = {};
  Object.keys(base).forEach(key => {
    if (typeof base[key] == "object" && data[key]) {
      result[key] = getBoth(base[key], data[key]);
    } else if (data[key]) {
      result[key] = data[key];
    }
  });
  return result;
}

console.log(getBoth(foo, bar));

答案 1 :(得分:1)

您可以这样尝试:

var foo = {
  "title": "Enter title",
  "info": {
    "released": "Enter year",
    "runtime": "Enter time"
  },
  "NOT_EXISTING_IN_DATA": "Test"
}

var bar = {
  "title": "Forrest Gump",
  "info": {
    "released": "1994",
    "runtime": "02:22",
    "awards": "3"
  },
  "genre": "Drama/Comedy-drama"
}



function isObj (a) {
  return a != null && a.constructor === Object;
}

function projectIntoSpec (spec, data) {
  return Object.keys(spec).reduce(function (acc, key) {
    if (data.hasOwnProperty(key)) {
      if (!isObj(data[key])) {
        // copy non-object values from data
        acc[key] = data[key];
        return acc;
      }
      // recursively copy object values
      acc[key] = projectIntoSpec(spec[key], data[key]);
    } else {
      // add things which are in the blueprint but not in the data
      acc[key] = spec[key];
    }
    return acc;
  }, {});
}



console.log(projectIntoSpec(foo, bar));

它将根据“ foo”中定义的所有内容创建数据的副本。如果它遇到数据中不存在的“ foo”中的键,则会复制“ foo”中的值。