Given a JS object like:
var obj = {
p1: "v1",
p2: "v2",
...,
pn: "vn"
}
What I would like to do is to obtain an iterator over all distinct pairs of properties (both names or values would work for me).
So I could have a function like:
function(va, vb) {
// do something with every pair
}
called once with each entry of the set of pairs ("v1", "v2"), ("v1", "v3"), ... , ("v1", "vn"), ("v2", "v3"), ... , ("v2", "vn"), ... , ("vn-1", "vn"). (A total of n(n - 1)/2 times)
The trivial solution is to have a double for ... in
loop and discard the repetitions inside, but that's not either fast or elegant.
If it was an array and not an object we could have a different kind of iteration, like:
var len = obj.length;
for (var i = 0; i < len - 1; i++) {
for (var j = i + 1; j < len; j++) {
// do something with obj[i], obj[j]
}
}
But I don't know any way to iterate an object like that (or if it would even make sense!).
Then, is there any fast and elegant way of doing this in javascript (or jQuery)?
Edit:
I don't want to get an iterator of (key, value) as suggested in some answers. I want an iterator over pairs of properties in an object.
I would like, for example, to run a check that verifies that every value is, at most, 10 units away from any other value.
function checkIsClose(v1, v2) {
return ((v1 - v2) < 10 && (v1 - v2) >= 0)) || ((v2 - v1) < 10 && (v2 - v1) >= 0);
}