casillas
casillas

Reputation: 16793

Javascript Object comparision

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"}]

Upvotes: 0

Views: 52

Answers (2)

Brian
Brian

Reputation: 3334

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

Upvotes: 0

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

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);

Upvotes: 2

Related Questions