Reputation: 169
Which is the best method for the mapping between 2 JSON files in angularJs I want to map beteween 2 JSON files and displayed it in my table.
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
}]
I want to map these files based on the year , and displayed it in my smart-table. Which is the best solution for this problem?
Upvotes: 0
Views: 245
Reputation: 113
Merging two JSON Objects:
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.
Merging with same properties:
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 }
Upvotes: 0
Reputation: 2727
Below code can be utilised for merging two 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);
Upvotes: 0
Reputation: 77910
You can use loadash:
var result = _.map(a, function(item) {
return _.merge(item, _.find(b, ['year', item.year]));
});
Output:
[
{
"year": 2013,
"doctor": "Dr. Smith",
"illness": "Flu",
"apptdate": "3/12/2013",
"details": "Patient had flu for 5 days. No medicines prescribed",
"cost": 260
},
...
]
If you don't need cost
, replace _.merge
with _.assign
a.e.
var result = _.map(a, function(item) {
return _.assign(item, _.find(b, ['year', item.year]));
});
Upvotes: 0
Reputation: 5293
You can easily achieve this by using map
, assign
and find
:
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;
}));
});
}
Upvotes: 1