0

I have the following javascript object

myData={my_ID: "NSOfe",his_ID: "AuJ"}

I would like to compare my_Data and see whether or not I have same my_ID in the following javascript objects (myData_1). If there is, it will return true on the console.

myData1=[{my_ID: "NSOfe",his_ID: "suJ"},{my_ID: "NSOfew",his_ID: "kuJ"},{my_ID: "NSOfey",his_ID: "BuJ"}]

2 Answers 2

2

Then compare the my_ID attributes for the objects:

console.log(myData.my_ID === myData1.my_ID); // true

For many comparisons place your items into an array and use a for loop to go through them:

var dataArray = [ myData1, myData2, myData3 ];

for( var i = 0; i < dataArray.length; i++ )
    console.log(myData.my_ID === dataArray[i].my_ID);
Sign up to request clarification or add additional context in comments.

1 Comment

@ilyasUyanik Then place your objects in an array and go through them comparing them to myData. I've updated my answer to reflex that.
0

You can stringify the array and then simply do an indexOf call on it like so:

var myData=[{my_ID: "NSOfe",his_ID: "AuJ"},{my_ID: "NSOfe",his_ID: "AuJ"}];

var myDataString  = JSON.stringify(myData);

console.log(myDataString.indexOf('"my_ID":"NSOfe"') !== -1);
console.log(myDataString.indexOf('"my_ID":"NSOfe2"') !== -1);

Console ouput:

true
false

4 Comments

This doesn't work properly. JSON can only represent a small subset of JavaScript objects. e.g. dates, regular expressions and functions are not supported. Other than that, for large objects it's extremely inefficient, and your -1 check only checks if that particular string is anywhere in the object. This problem can be solved easily by just inspecting the object.
@Tiddo, It works very properly for the original question
Although it technically, by accident, works for the exact situation proposed in the original question, it cannot be extended for any other similar question and it will fail as soon as there is only a slight change to the code. E.g. as soon as nested objects come into play it won't work. But more importantly, it's just a very bad way to do it. There's a trivial, proper solution to this problem, and string comparison is not it. "It works" is not a good enough motivation for a solution.
@Tiddo, I don't want to talk to you no more, you empty headed animal food trough whopper! I fart in your general direction! You mother was a hamster and your father smelt of elderberries!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.