0

What is the best way to see if a row of data is within a JavaScript object.

I made a simple example down below.

data within appointment is the same as the first row of upcoming_appointments

upcoming_appointments = [{"DOB":"01-27-2002","name":"Judy, W." ,"PCD":"Dr-S"},
{"DOB":"08-15-1995","name":"John, V." ,"PCD":"Dr-C"},
{"DOB":"07-05-1992","name":"David, C.","PCD":"Dr-S"},
{"DOB":"01-15-2002","name":"Anna, S." ,"PCD":"Dr-J"},
{"DOB":"01-15-2002","name":"Jeff, D." ,"PCD":"Dr-P"}];
    
appointment = [{"DOB":"01-27-2002","name":"Judy, W." ,"PCD":"Dr-S"}];

if(upcoming_appointments.includes(appointment[0])){
    console.log('true');
}
else{
    console.log('false');
}

desired output

true

current output

false
bombombs
  • 593
  • 1
  • 13

2 Answers2

1

JavaScript can't deeply-compare objects with equality operation.

You can achieve the desired result in a variety of ways, but the easiest one I can think of right now is by converting the objects to JSON strings and then comparing with the "stringified" version of your object.

// Function definition
function isRecordPresent(record, array) {
  const jsonRecord = JSON.stringify(record);
  const jsonArray = array.map(record => JSON.stringify(record));

  return jsonArray.includes(jsonRecord);
}

// Implementation
isRecordPresent(appointment[0], upcoming_appointments);

Edit:

In Node.js you can. There's a built-in Node module called util that brings a useful method for what you want: util.isDeepStrictEqual(a, b)

const util = require('util');

const objA = { a: 1, b: { a: 2, b: 3 } };
const objB = { a: 1, b: { a: 2, b: 3 } };
const objC = { a: 1, b: { a: 2, b: 4 } };

util.isDeepStrictEqual(objA, objB); // true
util.isDeepStrictEqual(objA, objC); // false
Dami
  • 119
  • 1
  • 3
0

You'd have to compare objects' values as while they may look the same, they're different objects.

const upcoming_appointments = [{"DOB":"01-27-2002","name":"Judy, W." ,"PCD":"Dr-S"},
{"DOB":"08-15-1995","name":"John, V." ,"PCD":"Dr-C"},
{"DOB":"07-05-1992","name":"David, C.","PCD":"Dr-S"},
{"DOB":"01-15-2002","name":"Anna, S." ,"PCD":"Dr-J"},
{"DOB":"01-15-2002","name":"Jeff, D." ,"PCD":"Dr-P"}];
    
const appointment = [{"DOB":"01-27-2002","name":"Judy, W." ,"PCD":"Dr-S"}];

if(
  upcoming_appointments.some(ua => {
    for (let k in ua)
      if (ua[k] !== appointment[0][k]) return !1;
    return !0;
  })
) {
    console.log('true');
}
else {
    console.log('false');
}
Kosh
  • 16,966
  • 2
  • 19
  • 34