合并两个 json 格式基于

Merging two json format based on

我正在尝试合并 json 格式(最好使用下划线)但不确定如何完成。第一个json没有要映射的_id的指标。

JSON 1:

{
    "0001": {
        "answer": "sad"
    },
    "0002": {
        "answer": "sad1"
    }
}

JSON 2:

[
    {
        "_id": "0001",
        "question": "who am I"
    },
    {
        "_id": "0002",
        "question": "How old are you?"
    }
]

合并后的最终结果:

[
    {
        "_id": "0001",
        "question": "who am I",
        "answer": "sad"
    },
    {
        "_id": "0002",
        "question": "How old are you?",
        "answer": "sad1"
    }
]

对于方法,我尝试先将 JSON 1 转换为以下格式,但无法实现。

[
    {
        "_id": "0001",
        "answer": "sad"
    },
    {
        "_id": "0002",
        "answer": "sad1"
    }
]

好的,所以你可以做一个 foreach 来添加新的答案元素:

var json1 = {
    "0001": {
        "answer": "sad"
    },
    "0002": {
        "answer": "sad1"
    }
};

var json2 = [
    {
        "_id": "0001",
        "question": "who am I"
    },
    {
        "_id": "0002",
        "question": "How old are you?"
    }
];

json2.forEach(function(o) { 
    o.answer = json1[o._id].answer;
});

console.log(json2);

希望对您有所帮助 :D