如何使用JavaScript合并不同的JSON对象?

时间:2019-04-09 15:51:11

标签: javascript json merge

如何使用JavaScript合并这些JSON对象?

如果缺少一个键,则将null替换为值

转换自:

[{"dateData": "2019-04-08", "geriatricDepressionScaleTotalScoreData": "5"}, 
{"dateData": "2019-04-09", "geriatricDepressionScaleTotalScoreData": "2"}]

[{"dateData": "2019-04-08", "digitSpanTotalScoreData": "10"},
{"dateData": "2019-04-09", "digitSpanTotalScoreData": "12"}]

[{"dateData": "2019-04-09", "immediateRecallStoryAData": "4", 
"delayedRecallStoryAData": "6"}]

[{"dateData": "2019-04-08", "phonologicalTotalData": "30"},
{"dateData": "2019-04-09", "phonologicalTotalData": "4"}]

转换为:

[{"dateData": "2019-04-08", "geriatricDepressionScaleTotalScoreData": "5",
"digitSpanTotalScoreData": "10", "immediateRecallStoryAData": null,
"delayedRecallStoryAData": null, "phonologicalTotalData": "30"}, 
{"dateData": "2019-04-09", "geriatricDepressionScaleTotalScoreData": "2",
"digitSpanTotalScoreData": "12", "immediateRecallStoryAData": 4,
"delayedRecallStoryAData": 6, "phonologicalTotalData": "4"}]

2 个答案:

答案 0 :(得分:0)

您可以使用散播运算符之类的

var myArr = [{ "dateData": "2019-04-08", "geriatricDepressionScaleTotalScoreData": "5" }, { "dateData": "2019-04-09", "geriatricDepressionScaleTotalScoreData": "2" }];
    myArr.push(...[{ "dateData": "2019-04-08", "digitSpanTotalScoreData": "10" }, { "dateData": "2019-04-09", "digitSpanTotalScoreData": "12" }]);
    myArr.push(...[{ "dateData": "2019-04-09", "immediateRecallStoryAData": "4", "delayedRecallStoryAData": "6" }]);
    myArr.push(...[{ "dateData": "2019-04-08", "phonologicalTotalData": "30" }, { "dateData": "2019-04-09", "phonologicalTotalData": "4" }]);

    var final = JSON.stringify(myArr);
    console.log(final);

答案 1 :(得分:0)

您可以使用Array .map()函数将现有对象数组重新格式化为带有新格式化对象的新数组。

const arr = [{"dateData": "2019-04-08", "geriatricDepressionScaleTotalScoreData": "5"},
             {"dateData": "2019-04-09", "geriatricDepressionScaleTotalScoreData": "2"}];

const result = arr.map((el) => {
    const obj = {};
   obj['dateData'] = el.hasOwnProperty('dateData')?el['dateData'] :null;
   obj['geriatricDepressionScaleTotalScoreData'] = el.hasOwnProperty('geriatricDepressionScaleTotalScoreData')?el['geriatricDepressionScaleTotalScoreData'] :null;
   obj['digitSpanTotalScoreData'] = el.hasOwnProperty('digitSpanTotalScoreData')?el['digitSpanTotalScoreData'] :null;
   obj['immediateRecallStoryAData'] = el.hasOwnProperty('immediateRecallStoryAData')?el['immediateRecallStoryAData'] :null;
   obj['delayedRecallStoryAData'] = el.hasOwnProperty('delayedRecallStoryAData')?el['delayedRecallStoryAData'] :null;
   obj['phonologicalTotalData'] = el.hasOwnProperty('phonologicalTotalData')?el['phonologicalTotalData'] :null;

  return obj;
});