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
I think I understand what you are trying to achieve here.
How about the following one? It worked for me.
var result = arr2
.filter(function(objs) {
return ((objs.find((obj) => obj.ingredients === "a" ).max == 0.685)
&& (objs.find((obj) => obj.ingredients === "b" ).max == 14));
})
.reduce(function(a, b) {
return a.concat(b);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.