javascript - 使用嵌套数组过滤器组合过滤 JSON 数组

标签 javascript arrays json

我正在编写一段 JS 代码,它必须根据条件过滤 JSON 数据。我昨天发布了一个问题,但没有在 How to filter data from a json response 进行任何尝试,它被否决了,因为我没有尝试任何东西,所以我对此很满意。我尝试过使用过滤器,但不幸的是我有一个带有 in array 的数组,但我被困住了。这是我的代码。

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));

当我运行此代码时,得到的结果为“6”。

但这里我的条件是这样的 ((obj.max == 0.685 && obj.ingredients === "a") && (obj.max == 14 && obj.ingredients === "b ")),但这不会返回任何内容。

这里的预期输出是“6”

这是一个工作 fiddle https://jsfiddle.net/vjt45xv4/14/

请让我知道我哪里出了问题以及如何解决这个问题。

谢谢

最佳答案

我想我明白你想在这里实现什么目标。

下面这个怎么样?它对我有用。

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);
  });

关于javascript - 使用嵌套数组过滤器组合过滤 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48295232/

相关文章:

javascript - 在 Javascript 中填充的可折叠项将不起作用

javascript - 在 JavaScript 中调用组合框值

arrays - SwiftUI 复选标记单行

javascript - 转换Json数据

javascript - 将 JSON 保存在 HTML 列表项中

javascript - 使用 ng-repeat 显示 JSON 数组中的数据

javascript - 选择日期后如何删除 html 5 中的 X 标记(清除按钮)[输入类型 ="date"]

javascript - 跨域监听 iframe 中的 keydown 事件

javascript - 使用字符串中数组的每个元素组成标准化的句子

arrays - 有时将子数组列表中的项目分发到其他子数组/作品然后随机出错