I'm writing a JS code that has to filter JSON data based on a condition. I've posted a question yesterday but without trying anything at How to filter data from a json response, it was down voted and since I didn't try anything I am good with it. I've tried using the filter, but unfortunately I've got an array with in array and here I'm stuck. Here is my code.
var arr2 = [
[{
"max": "0.685",
"target_state": "6",
"ingredients": "a",
"rule_no": "7",
"id": "18"
}, {
"max": "14",
"target_state": "6",
"ingredients": "b",
"rule_no": "7",
"id": "17"
}],
[{
"max": "14",
"target_state": "7",
"ingredients": "b",
"rule_no": "8",
"id": "19"
}, {
"max": "1.36",
"target_state": "7",
"ingredients": "a",
"rule_no": "8",
"id": "20"
}]
];
var result = arr2.reduce(function(a, b) {
return a.concat(b);
})
.filter(function(obj) {
return (obj.max == 0.685 && obj.ingredients === "a")
});
alert(JSON.stringify(result[0].target_state));
when I run this code, I get the result as "6".
But here my condition is something like this ((obj.max == 0.685 && obj.ingredients === "a") && (obj.max == 14 && obj.ingredients === "b")), but this is not returning anything.
Here the expected output is "6".
Here is a working fiddle https://jsfiddle.net/vjt45xv4/14/
Please let me know where am I going wrong and how can I fix this.
Thanks
(...) || (...). Ifobj.maxis 0.685, it cannot be 14. Always try to write an English version of condition. It will always help in solving them.((obj.max == 0.685 && obj.ingredients === "a") && (obj.max == 14 && obj.ingredients === "b"))is interpreted asmaxvalue should be0.685andingredientsshould beaandmaxvalue should be14andingredientsshould beb==in order to compare a number to a string. If you want to compare a string value to a number, parse the string:Number(obj.max) === 0.685[[{}, {}],[{}, {}]]and here I want to check the internal arrays matching the condition(both the internal arrays should satisfy it) and return the result.