简体   繁体   中英

How can I compare two objects and add the missed values?

I would like to compare two objects by the object value "Datum". In my case I would like to check if the "Datum" value in "mengeGes" is also in the "v" object. If not, then add the values of the "mengeGes" object to the "v" object.

In my example, the object with the "Datum" 2022-02-22 should add from the mengeGes to v:

 const mengeGes = [{ "Datum": "2022-02-20", "Datum_str": "20.02.2022" }, { "Datum": "2022-02-21", "Datum_str": "21.02.2022" }, { "Datum": "2022-02-22", "Datum_str": "22.02.2022" } ] var v = [{ "Datum": "2022-02-20", "Datum_str": "20.02.2022", "xx": 4 }, { "Datum": "2022-02-21", "Datum_str": "21.02.2022", "xx": 4 } ] // The expected result: v = [{ "Datum": "2022-02-20", "Datum_str": "20.02.2022", "xx": 4 }, { "Datum": "2022-02-21", "Datum_str": "21.02.2022", "xx": 4 }, { "Datum": "2022-02-22", "Datum_str": "22.02.2022" } ] console.log(v)

We can create an array containing the 'missing' objects like so:

var missing = mengeGes.filter(menge => v.filter(vv => vv.Datum === menge.Datum).length === 0);

Here we loop over mengeGes and filter it by checking if there is an object in v where Datum maches


Then, we can combine that array with the existing v :

var combine = [ ...v, ...missing ];

 const mengeGes = [{ "Datum": "2022-02-20", "Datum_str": "20.02.2022" }, { "Datum": "2022-02-21", "Datum_str": "21.02.2022" }, { "Datum": "2022-02-22", "Datum_str": "22.02.2022" } ] var v = [{ "Datum": "2022-02-20", "Datum_str": "20.02.2022", "xx": 4 }, { "Datum": "2022-02-21", "Datum_str": "21.02.2022", "xx": 4 } ]; var missing = mengeGes.filter(menge => v.filter(vv => vv.Datum === menge.Datum).length === 0); var combine = [ ...v, ...missing ]; console.log(combine);


Result:

[
  {
    "Datum": "2022-02-20",
    "Datum_str": "20.02.2022",
    "xx": 4
  },
  {
    "Datum": "2022-02-21",
    "Datum_str": "21.02.2022",
    "xx": 4
  },
  {
    "Datum": "2022-02-22",
    "Datum_str": "22.02.2022"
  }
]

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