Reputation: 3014
How can I compare the contents of two JSON files in Angular and achieve the following result:
Let's say that I have a default.json file that looks like this:
default.json
{
"name": "John"
"age": 30,
"car1": "Ford"
"car2": "BMW"
"car3": "Fiat"
}
And another specific.json file that looks like this:
specific.json
{
"name": "Doe",
"car1": "Tesla",
"car4": "Mercedes"
}
The default.json contains always all possible keys and the specific.json the keys, which should be overwritten and additional keys, which are not contained in the default.json (in my example: "car4").
Now the following should be checked by the comparison:
If a specific key (in my example "name" and "car1") has a different value in the specific.json than in the default.json for the same keys, then these values should be overwritten and used. Otherwise always the default values from the default.json and the additional values from the specific.json of course (in my example "car4").
At the end both files should be used, so the specific.json serves only as an update or extension of the default.json. I need this functionality in an Angular app, where I have to compare two JSON files and then use the ngx-translate library to provide specific translations based on specific business cases of the application. Check also my question about this topic please if you want: Translations based on specific keys in custom JSON files and business cases with ngx-translate (Angular 7)
I hope I could explain it well :)
Upvotes: 0
Views: 2058
Reputation: 2512
Use es6 spread operator to merge (And override) objects
const defaultObj = {
name: 'John',
age: 30,
car1: 'Ford',
car2: 'BMW',
car3: 'Fiat'
};
const specificObj = {
name: 'Doe',
car1: 'Tesla',
car4: 'Mercedes'
}
console.log({ ...defaultObj, ...specificObj });
Upvotes: 1
Reputation: 6692
This is not related with Angular, but with JS.
Below example how to do it with objects.
let def = {
"name": "John",
"age": 30,
"car1": "Ford",
"car2": "BMW",
"car3": "Fiat"
};
let specific = {
"name": "Doe",
"car1": "Tesla",
"car4": "Mercedes"
}
function compose(def, spec) {
return Object.assign(def, spec);
}
console.log(compose(def, specific));
Output:
/*
{
name: 'Doe',
age: 30,
car1: 'Tesla',
car2: 'BMW',
car3: 'Fiat',
car4: 'Mercedes'
}
*/
Upvotes: 1