简体   繁体   English

如何在javascript中合并2个json对象

[英]How to merge 2 json objects in javascript

example: Below there are 2 json objects with different values and I want to make it as one final Json object and append new value to the final result示例:下面有 2 个具有不同值的 json 对象,我想将其作为一个最终的 Json 对象并将新值附加到最终结果

let json1= { "b":"test1", "a":"test3", "type":"sample1" }让 json1= { "b":"test1", "a":"test3", "type":"sample1" }

let json2= { "b":{ "endDate":"ddd1", "startDate":"dd01" }, "a":{ "endDate":"31", "startDate":"01" }, "type":"sample2" }让 json2= { "b":{ "endDate":"ddd1", "startDate":"dd01" }, "a":{ "endDate":"31", "startDate":"01" }, "type ":"sample2" }

Expected results should be like below预期结果应如下所示

let result = { "b":{ "endDate":"ddd1", "startDate":"dd01", "XYZ":"test1" }, "a":{ "endDate":"31", "startDate":"01", "XYZ":"test3" }, } let result = { "b":{ "endDate":"ddd1", "startDate":"dd01", "XYZ":"test1" }, "a":{ "endDate":"31", "startDate" :"01", "XYZ":"test3" }, }

Can anyone help please using JavaScript or loadash functionality任何人都可以帮忙请使用 JavaScript 或 loadash 功能



Can be as simple as this:可以像这样简单:

 let Object1 ={"b":"test1","a":"test3","type":"sample1"};let Object2 ={"b":{"endDate":"ddd1","startDate":"dd01"},"a":{"endDate":"31","startDate":"01"},"type":"sample2"} let Object3 = Object2; for (let i in Object3){ Object3[i]["XYZ"] = Object1[i] } Object3["type"] = "12345" console.log(Object3)

You can use the rest operator to remove type property and then assign values from 1st object to new property of the merged object您可以使用 rest 运算符删除类型属性,然后将值从第一个对象分配给合并对象的新属性

let mergeObjects = (a, b) => {

    let {type, ...rest} = b; //remove type property
    for(let prop in rest){
        if(a[prop]){
            rest[prop].xyz = a[prop]; 
        }
    }
    return rest;
}

let Object3= mergeObjects(Object1, Object2);
console.log(Object3);

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

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