简体   繁体   中英

How to compare the contents of two JSON files with TypeScript?

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 :)

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' 
}
*/

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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM