如何动态合并两个不同深度的对象 [英] how to merge two two objects with different depths dynamically

查看:41
本文介绍了如何动态合并两个不同深度的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个一模一样的东西

I have two identical objects with me

let a  = {
  title : "developer",
  startDate:{ month :’jan’}
}

let b  = {
  title :{
    value: ""
  } ,
startDate :{month:{value:""}}
}

我需要动态合并这两个以获得如下所示的对象

i need to merge dynamically these two to get object like below

let c  = {
  title :{
    value: "developer"
  } ,
startDate:{
  month:{ value:" jan"}}
}

推荐答案

您不需要对象 b 因为它只是对象 a 的副本,并带有额外的 'value' 属性.
您可以遍历完整的a 对象,然后将b 对象中的值进行深度复制.

You don't require object b because it's just a replica of object a with extra 'value' property.
You can traverse the complete a object and then deep copy the value in the b object.

我为此编写了一个递归方法,您可以遍历该对象的最后一级并将值复制到另一个对象中.

I wrote a recursive method for this where you can traverse to the last level of the object and copy the value in another object.

function mergeObj(sourceObj, newObj) {

  Object.keys(sourceObj).forEach(key => {
    if (sourceObj[key] && typeof sourceObj[key] === 'object') {
      newObj[key] = {};
      mergeObj(sourceObj[key], newObj[key]);
    } else {
      // updating properties
      newObj[key] = {};
      newObj[key]['value'] = sourceObj[key];
    }
  });
}

let a  = {
  title : "developer",
  startDate:{ month :'jan'}
};
let b  = {};

mergeObj(a,b);

console.log(b);

这篇关于如何动态合并两个不同深度的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆