Maybe a silly question, Is there a trick to correctly and easily place more than one return true/false in a nested if(){if(){if(){}}} statement?
Just an example:
One array: collection=[{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 },{"a":1,"b":1,"c":2}];
One object: source= { "a": 1, "c": 2 };
Question: use Array.filter(conditionFunc) to match element from source to collection: display those element with the same property and the same value from collection array. I have some code below but my question is:
1 Why I should return true here?
2 If there is a if(){if(){}}, where should I correctly return true?
the answer should return [{ "a": 1, "b": 2, "c": 2 },{"a":1,"b":1,"c":2}]
Wrong code below: Why the position to place "return true" after the first "return false" is wrong?
var key=Object.keys(source);
collection.filter(matchFun);
function matchFun(item) {
for (var i = 0; i < key.length; i++) {
if (!item.hasOwnProperty(key[i]) || !source[[key[i]]] == item[key[i]]) {
return false;
}return true; //this is wrong, but I don't know why?
}
}
This is right code, but if there are more if(){} nested inside another if(){} I will get tripped where to "return true" the second time in different cases.Great thanks for anyone who can explain the mechanism to me
key=Object.keys(source);
collection.filter(matchFun);
function matchFun(item) {
for (var i = 0; i < key.length; i++) {
if (!item.hasOwnProperty(key[i]) || !source[[key[i]]] == item[key[i]]) {
return false;
}
} return true;
}