Currently, I am in the process of developing a JavaScript code that aims to filter JSON data based on a specific condition. Yesterday, I had posted a question seeking guidance on this matter How to filter data from a json response. However, since I had not made any attempts prior to posting the question, it received downvotes which I completely understand.
I experimented with using the 'filter' method, but encountered an issue where I ended up with an array within another array, leaving me stuck at that point. Below is the snippet of 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 executing this code, it provides the output as "6". Although, my desired condition involves checking for multiple scenarios such as
((obj.max == 0.685 && obj.ingredients === "a") && (obj.max == 14 && obj.ingredients === "b"))
, sadly it does not return anything.
The expected outcome here should be "6"
.
You can view a working fiddle demonstrating this scenario: https://jsfiddle.net/vjt45xv4/14/
Please provide your insights on where I might be going wrong and how could I go about rectifying this problem.
Thank you!