合并没有新密钥的JSON对象 [英] merge JSON objects without new keys

查看:73
本文介绍了合并没有新密钥的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何合并两个JSON对象但不包含第一个对象中不存在的属性?

How to merge two JSON objects but do not include properties that don't exist in the first Object?

var obj1 = { x:'', y:{ a:'', b:'' } };
var obj2 = { x:1, y:{ a:1, b:2, c:3 }, z:'' };



输出



Output

obj1 = { x:1, y:{ a:1, b:2 } };



ps。对象的方法称为 preventExtensions 但它似乎只是阻止属性的立即扩展而不是更深层次的扩展。


ps. There is a method for Objects called preventExtensions but it appears to only block the immediate extension of properties and not deeper ones.

推荐答案

/*
    Recursively merge properties of two objects 
    ONLY for properties that exist in obj1
*/

var obj1 = { x:'', y:{ a:'', b:'' } };
var obj2 = { x:1, y:{ a:1, b:2, c:3 }, z:'' };

function merge(obj1, obj2) {
    for( var p in obj2 )
        if( obj1.hasOwnProperty(p) )
            obj1[p] = typeof obj2[p] === 'object' ? merge(obj1[p], obj2[p]) : obj2[p];

    return obj1;
}

merge(obj1, obj2 );
console.dir( obj1 ); // { x:1, y:{ a:1, b:2 } }

这篇关于合并没有新密钥的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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