Home > Software engineering >  Javascript comparing at least one identical pairs in an object
Javascript comparing at least one identical pairs in an object

Time:11-11

I have two dictionaries (object in JS?), and I want to compare them.

In a while loop, I want to print True if at least one of the pairs is identical (i.e. the dictionary below), as opposed to the whole dictionary being identical (but if the whole dict is identical the statement must still be True obviously):

my_dict = {"Text1":"Text1", "Text2":"Text3", "text5":"text5"}

I know in python it would be like that:

while any(key == value for key, value in my_dict.items()):
    ...
else:
    ...

But I can’t get my hands on the correct syntax for JavaScript.

CodePudding user response:

for(var key in obj){
    if(key === obj[key]){
        //Do Something
    } else {
        //Do Something Else
    }
}

That iterates through the object, and if the key is equal to the value, then it does something, otherwise it does something else.

CodePudding user response:

You can use the some() function on JavaScript arrays which is identical to any from Python I think.

let my_dict = {"Text1":"Text1", "Text2":"Text3", "text5":"text5"}

let same_exists = Object.keys(my_dict).some((key) => key === my_dict[key])
console.log(same_exists)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

With Object.entries() and some() this is a one-liner:

let my_dict = {"Text1":"Text1", "Text2":"Text3", "text5":"text5"}

let answer = Object.entries(my_dict).some(([key,value]) => key == value);

console.log(answer)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related