Check if JSON contains value pair from another JSON

Hi I’m trying to compare 2 JSONs whether there are two values in a combination or not.

For e.g.

wechselwirkungen

[{"1": 1234, "2": 5678}, {"1": 2222, "2": 1111}, {"1": 2222, "2": 5678}]

medArray

[{"Code": 1234}, {"Code": 5678}, {"Code": 2222}]

Expected Output: In this example it should return the arrays with index 0 and 2 of ‘wechselwirkungen’

[{"1": 1234, "2": 5678}, {"1": 2222, "2": 5678}]

I’ve tried with two nested loops but It doesn’t work

function findPairs(medArray) {

  for(var i=0;i<wechselwirkungen.length;i++){
    for (var j=0;j<medArray.length;j++){
     console.log("test", wechselwirkungen[i][1].includes(medArray[j].Code))
      if(wechselwirkungen[i][1].includes(medArray[j].Code) && wechselwirkungen[i][2].includes(medArray[j].Code)){
      console.log('test wechselwirkungen: ' + wechselwirkungen[i] + ' medArray:' + medArray[j]);
    }
   }
  }

}

Thank you for your hints

>Solution :

You could check all properties and filter the array.

const
    wechselwirkungen = [{ 1: 1234, 2: 5678 }, { 1: 2222, 2: 1111 }, { 1: 2222, 2: 5678 }],
    medArray = [{ Code: 1234 }, { Code: 5678 }, { Code: 2222 }],
    codes = medArray.map(({ Code }) => Code),
    result = wechselwirkungen.filter(o => Object
        .values(o)
        .every(v => codes.includes(v))
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Leave a Reply