简体   繁体   English

通过键比较将对象复制到另一个对象

[英]Copying an object to another by key(s) compare

I am trying to copy a object to another by comparing it's key. 我试图通过比较它的键将一个对象复制到另一个对象。 according to me the key can be nested any of the object node. 根据我的说法,键可以嵌套在任何对象节点上。 still I am require to copy them in another object by just comparing their key . 我仍然需要通过比较它们的key将它们复制到另一个对象中。

they object key in any level in the object tree. 它们在对象树中的任何级别上都将对象作为键。

Is this possible? 这可能吗?

here is my try: 这是我的尝试:

var extend = function (original, context, key) {
  for (key in context)
    if (context.hasOwnProperty(key))
      if (Object.prototype.toString.call(context[key]) === '[object Object]')
        original[key] = extend(original[key] || {}, context[key]);
      else
        original[key] = context[key];
  return original;
};

var firstObject = {
    key1 : 'ar',
    key2 : 'value2',
    address:{
    "street" : "D15 Road"
    "sub":{"name":"Stockoverflow"}
    }
};

var secondObject = {
    name:"",
    street:"",
    key3 : 'value3',
    key4 : 'value4'
};
var x = extend(secondObject, firstObject )
console.log( 'extend', x );

In my above try, still the street:"", name:"" not updated. 在我上面的尝试中, street:"", name:""尚未更新。

This should do the trick: 这应该可以解决问题:

 const source = { key1: 'a', common1: 'value1', a: { b: { c: { common2: 'value2' } } } }; const dest = { key2: 'b', common1: null, common2: null }; function extend(dest, source) { Object.entries(source).forEach(([key, value]) => { if (typeof value === 'object') { extend(dest, value); } else if (dest.hasOwnProperty(key)) { dest[key] = value; } }); } extend(dest, source); console.log(dest); 

Basically, looping through them you only have two options: it's an object or it's key matches. 基本上,遍历它们只有两个选择:一个对象或键匹配。

If it is an object, we just recursively call extend . 如果它是一个对象,我们只需递归调用extend If it's key matches, then we set the value. 如果键匹配,则设置值。

If you want to be able to do this with objects as values (ie, common1 could be an object instead of a primitive), just switch the two in the if statement. 如果您希望能够使用对象作为值来执行此操作(即, common1可以是对象而不是原始对象),只需在if语句中将两者切换即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM