0

Let's say I have two api calls that returns a list of objects

const userResult1 = {1: {..} ,2: {..} 3: {..}}
const userResult2 = {3: {..} ,4: {..} 5: {..}}

either one could return null. What I'm currently doing is:

if (userResult1 || userResult2 === null) {
  //false
} else {
 
  const dataset = [
    Object.keys(userResult1 ),
    Object.keys(userResult2 ),
  ];
  const result = checkIfDuplicateExists(dataset);
  console.log(result) //true or false
}

I did not have the if statement before which used to throw Cannot convert undefined or null to object but adding the if statement prevents this. Is this a good approach?

JonJon
  • 169
  • 1
  • 1
  • 10
  • 4
    `if (userResult1 === null || userResult2 === null)` – Jeremy Thille Nov 02 '20 at 09:49
  • `userResult1 || userResult2 === null` means "if `userResult1` is truthy or `userResult2` is `null`" which in turn means that if `userResult1` is `null`, but `userResult2` isn't, you're not going inside the body of the function. Same thing happens if `userResult1` is not `null` while `userResult2` is. – VLAZ Nov 02 '20 at 09:52
  • @VLAZ and Jeremy looks like you've method spotted my mistake. I just realised that data looks like this [[array1],[array2]] how can I push all ids to a new array so it's a flat structure? – JonJon Nov 02 '20 at 10:00
  • [Merge/flatten an array of arrays](https://stackoverflow.com/q/10865025) - the easiest way is to do `arr.flat()`. If your arrays are nested deeper `arr.flat(3)` (for three levels deep) or `arr.flat(Infinity)` (any depth). [Example](https://jsbin.com/tigavorave/edit?js,console) – VLAZ Nov 02 '20 at 10:01
  • @VLAZ thank you vlaz! just learned a number of new things especially the truthy – JonJon Nov 02 '20 at 10:05

2 Answers2

0

You could use

if (userResult1 && userResult2) {
   return Object.keys(userResult1).some(
       Set.prototype.has,
       new Set(Object.keys(userResult2))
   );
}
return false;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

If you're aren't sure if the type of value you will be receiving, it will be more wise to check for the perticular data type you want.

Since you're expecting an object.

Doing:

if(userResult1 && userResult2) {
    return true;
}
return false;

The above code will always be truthy if the userResult1 and userResult2 is a value other than null and undefined

So I will suggest you use a more convenient method for the check, e.g. if you are expecting an object the test the value with the below function:

function isPlainObject(val) {
    return toString.call(val) === '[object Object]'
}

The above will only return true on plain object e.g {}

Fritzdultimate
  • 372
  • 2
  • 11