AngularJs中2个json文件之间的映射

时间:2017-09-27 11:34:46

标签: angularjs json

哪个是angularJs中2个JSON文件之间映射的最佳方法 我想在2个JSON文件之间进行映射并将其显示在我的表中。

JSON 1

[{
    "year": 2013,  
    "doctor": "Dr. Smith", 
    "illness": "Flu", 
    "apptdate": "3/12/2013",
    "details":"Patient had flu for 5 days. No medicines prescribed"
}, {
    "year": 2014,  
    "doctor": "Dr. ram", 
    "illness": "fever", 
    "apptdate": "31/12/2014",
    "details":"Patient had flu for 5 days. No medicines prescribed"
}, {
    "year": 2015,  
    "doctor": "Dr. rom", 
    "illness": "headache", 
    "apptdate": "3/12/2015",
    "details":"Patient had flu for 5 days. No medicines prescribed"
}, {
    "year": 2016,  
    "doctor": "Dr. zen", 
    "illness": "fever", 
    "apptdate": "21/12/2016",
    "details":"Patient had flu for 5 days. No medicines prescribed"
}]

JSON 2

[{
    "year": 2013,  
    "cost": 260
}, {
    "year": 2014,  
    "cost": 360
}, {
    "year": 2015,  
    "cost": 102
}, {
    "year": 2016,  
    "cost": 180
}]

我想根据年份映射这些文件,并将其显示在我的智能表中。 哪个是这个问题的最佳解决方案?

4 个答案:

答案 0 :(得分:1)

您可以使用mapassignfind轻松实现此目的:

function merge(json1, json2) {
    if (!json1 || !json1.length || !json2 || !json2.length) {
        return [];
    }
    return json1.map((current) => {
        return Object.assign(current, json2.find((el) => {
            return el.year === current.year;
        }));
    });
}

答案 1 :(得分:0)

您可以使用loadash

var result = _.map(a, function(item) {
    return _.merge(item, _.find(b, ['year', item.year]));
});

使用mapfindmerge

Demo Fiddle

输出:

[
  {
    "year": 2013,
    "doctor": "Dr. Smith",
    "illness": "Flu",
    "apptdate": "3/12/2013",
    "details": "Patient had flu for 5 days. No medicines prescribed",
    "cost": 260
  },
...
]

如果您不需要cost,请将_.merge替换为_.assign a.e。

var result = _.map(a, function(item) {
    return _.assign(item, _.find(b, ['year', item.year]));
});

答案 2 :(得分:0)

下面的代码可用于合并两个json:

function merge(obj) {
    var sources = [].slice.call(arguments, 1);
    sources.forEach(function (source) {
      for (var prop in source) {
        target[prop] = source[prop];
      }
    });
    return obj;
}

var result = merge({}, json1, json2);

答案 3 :(得分:0)

合并两个JSON对象:

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, target object itself is changed.

合并相同的属性:

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

Source