Reputation: 451
I have a json object example
var obj = { a: "sample", b: "sample", c: "sample" };
and I want to check each key if they have the same values.
if(a === b || b === c || c === a){
console.log("Error");
}
is there a better way of checking these values? Any ideas would be helpful. Thank you!
Upvotes: 1
Views: 172
Reputation: 13356
You can use Object.keys and array.every and compare all values with the first one:
var obj = { a: "sample", b: "sample", c: "sample" };
var keys = Object.keys(obj);
var first = obj[keys[0]]
var sameValue = keys.every(key => obj[key] === first);
console.log(sameValue);
EDIT:
In case you want to return true if at least two properties have the same value:
var obj = { a: "sample", b: "saxmple", c: "sample" };
var keys = Object.keys(obj);
var sameValue = keys.some((key, index) => keys.some((otherKey, otherIndex) => obj[key] === obj[otherKey] && index !== otherIndex));
console.log(sameValue);
Upvotes: 1
Reputation: 18699
The code you posted will never print Error
.
You are referencing values that do not exist.
Fix this with:
if(obj.a === obj.b || obj.b === obj.c || obj.c === obj.a){
console.log("Error");
}
You can also do it with:
var firstObj = '';
var i = 0;
var areDifferent = false;
for var prop in obj {
if (i == 0){
firstObj = obj[property]
}
if (firstObj != obj[property]){
areDifferent = true;
}
i++;
}
if (areDifferent){
//your code here
}
The code above will run through all obj
properties, to check if all of them are equal to the first one - which means, that are of them are equal.
Upvotes: 1
Reputation: 1
try this _.every from Underscore.js
every_.every(list, [predicate], [context])
Returns true if all of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a false element is found.
_.every([2, 4, 5], function(num) { return num % 2 == 0; }); => false
in ur case u should check value of the first element of "obj" with all next elements in "obj"
Upvotes: -1