简体   繁体   English

使用组合的嵌套数组过滤器过滤JSON数组

[英]Filter JSON arrays with nested array filters combined

I'm writing a JS code that has to filter JSON data based on a condition. 我正在编写一个必须根据条件过滤JSON数据的JS代码。 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. 我昨天发布了一个问题,但是没有尝试如何过滤json响应中的数据 ,它被否决了,因为我什么都没尝试,所以我很满意。 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". 运行此代码时,结果为“ 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. 但是这里我的情况是这样的((obj.max == 0.685 && obj.ingredients === "a") && (obj.max == 14 && obj.ingredients === "b")) ,但是没有返回任何东西。

Here the expected output is "6" . 在此,预期输出为"6"

Here is a working fiddle https://jsfiddle.net/vjt45xv4/14/ 这是一个工作的小提琴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);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM