合并两种基于json的格式

时间:2016-04-07 03:56:51

标签: javascript jquery json underscore.js

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

JSON 1:

/proc/pid/maps

JSON 2:

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

合并后的最终结果:

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

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

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

1 个答案:

答案 0 :(得分:1)

好的,所以你可以做一个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