Javascript 基于xml的两种json格式的合并

Javascript 基于xml的两种json格式的合并,javascript,jquery,json,underscore.js,Javascript,Jquery,Json,Underscore.js,我正在尝试合并json格式(预先使用下划线),但不确定如何合并。第一个json没有要映射的_id的指示符 JSON 1: { "0001": { "answer": "sad" }, "0002": { "answer": "sad1" } } JSON 2: [ { "_id": "0001", "question": "who am I" }, { "_i

我正在尝试合并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

arr.map(o=>{o.answer=obj[o.\u id].answer;return o;})一样简单
。但我什么都没试过。请看一下JSON 1,它不是数组。@Fabricio是的,我很清楚这一点。很抱歉,我的代码有误。请检查我是否已将a替换为其中的json1。它现在对我起作用了。@stackdisplay-
json1
只是一个变量名。请记住,JSON只是一个标准的JS对象,可以像一个JS对象一样使用。@evolutionxbox,你是对的,json1的类型是一个标准对象,但是如果你看一下我循环使用的代码
json2
,forEach不超过
json1
。。。。所以
typeof json2.forEach==“undefined”
为false。请再次检查代码;)