comparing javascript objects

Asked

Viewed 23 times

0

to compare objects in javascript, I could turn these objects into strings and then compare them? would the result be correct? follows below what I did:

let equalsString = (a, b) => {
    let atostring = JSON.stringify(a)
    let btostring = JSON.stringify(b)
    if (atostring === btostring) {
        return true
    } 
    return false
}

var obj = {here: {is: "an"}, object: 2};
var obj2 = {here: 1, object: 2};
console.log(equalsString(obj, obj2));
// false
console.log(equalsString(obj, obj));
// true
console.log(equalsString(obj, {here: {is: "an"}, object: 2}));
// false

if someone could clear my head around here, I’d be immensely grateful...


taking into consideration what was suggested, I arrived at this script, however it is not correct and I cannot identify the error.

let deepEqual = (a, b) => {
    let aKeys = Object.keys(a);
    let bkeys = Object.keys(b);
    if (aKeys.length !== bkeys.length) {
        return false
    }
    let equals = aKeys.some((chave) => {
        return a[chave]!== b[chave]
    });
    return !equals
}
let obj = {here: {is: "an"}, object: 2};
let obj2 = {here: {is: "an"}, object: 2};
let obj3 = obj2;
console.log(deepEqual(obj, obj));
// true
console.log(deepEqual(obj, obj2));
// false
console.log(deepEqual(obj2, obj3));
// true
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// false

in my view (that everything indicates is wrong), all the objects I am going through are equal, but the return is false...

  • If it’s a simple object, you can do it that way; otherwise, no. The way you did, it wouldn’t work, for example, on objects that have properties that return a function. Example. https://stackoverflow.com/questions/1068834/object-comparison-in-javascript

  • fix: the last return would be TRUE and not false. typing error.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.