将多个对象合并为一个对象

时间:2017-08-31 12:58:39

标签: javascript arrays node.js

我有两个从数据库返回的对象,我想将这个对象合并为一个对象,例如:

{
            "id": 4,
            "first_name": "zura",
            "last_name": "kacitadze",
            "personal_no": "21001033391",
            "email": "zuri.kacitadze@gmail.com",
            "gender": "MALE",
            "address": "SANZONA",
            "birthdate": "2017-09-14T20:00:00.000Z",
            "phone": "598637625"
        }
第二个:

{
            "id": 684,
            "create_date": "2017-08-31T07:41:32.000Z",
            "update_date": null,
            "person_no": "21001033391",
            "status_id": 1,
            "payment_status_id": null,
            "payment_type": null,
            "comment": null,
            "res_type": null
        }

我想得到像这样的结果

{
{
first object 
},
{
second object
}
}

2 个答案:

答案 0 :(得分:1)

您可以使用数组执行此操作,然后使用Object.assign()将其转换为对象



let a = {
            "id": 4,
            "first_name": "zura",
            "last_name": "kacitadze",
            "personal_no": "21001033391",
            "email": "zuri.kacitadze@gmail.com",
            "gender": "MALE",
            "address": "SANZONA",
            "birthdate": "2017-09-14T20:00:00.000Z",
            "phone": "598637625"
        };


let b = {
            "id": 684,
            "create_date": "2017-08-31T07:41:32.000Z",
            "update_date": null,
            "person_no": "21001033391",
            "status_id": 1,
            "payment_status_id": null,
            "payment_type": null,
            "comment": null,
            "res_type": null
        }
let result = [a, b];
console.log(result);
let result2 = Object.assign({}, result);
console.log(result2);




答案 1 :(得分:0)

我认为您的期望如下

var data={
          "firstObject":{},
          "secondObject":{}
        };

data.firstObject={
            "id": 4,
            "first_name": "zura",
            "last_name": "kacitadze",
            "personal_no": "21001033391",
            "email": "zuri.kacitadze@gmail.com",
            "gender": "MALE",
            "address": "SANZONA",
            "birthdate": "2017-09-14T20:00:00.000Z",
            "phone": "598637625"
          };


data.secondObject={
            "id": 684,
            "create_date": "2017-08-31T07:41:32.000Z",
            "update_date": null,
            "person_no": "21001033391",
            "status_id": 1,
            "payment_status_id": null,
            "payment_type": null,
            "comment": null,
            "res_type": null
        };
        
console.log(data.firstObject);
console.log(data.secondObject);