Ad
Comparing Two Objects Does Not Give Correct Results
i am trying to compare two objects. The ages are different but still says they are same.. here is my code
var personA =
{
name: "Josh Kloss",
age: 33
}
var personmB =
{
name: 'Josh Kloss',
age: 43
}
function compareTwoPeople(a, b) {
var person1 = Object.keys(a);
var person2 = Object.keys(b);
if (person1.length !== person2.length) {
console.log("They are not same");
}
else {
for (var i = 0; i < person1.length; i++) {
if (person1[i] === person2[i]) {
console.log("They are same");
}
}
}
}
compareTwoPeople(personA, personmB);
How can i compare these two object... Thanks.
Ad
Answer
Close, just need to tidy up the comparison a little bit to get at the object value using the key and the iterator.
var personA =
{
name: "Josh Kloss",
age: 33
};
var personB =
{
name: 'Josh Kloss',
age: 43
};
function compare(a, b) {
var aKeys = Object.keys(a),
bKeys = Object.keys(b);
if(aKeys.length != bKeys.length) return false;
for(var i = 0; i < aKeys.length; i++) {
if(a[aKeys[i]] != b[bKeys[i]]) return false;
}
return true;
}
compare(personA, personB);
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad