javascript - 过滤特定值的嵌套数组

标签 javascript arrays

我有一个像这样的简单数组:

const test = [{
  test: 1,
  key: [{
    yes: true,
    no: null
  },{
    yes: true,
    no: null
  },{
    yes: false,
    no: null
  }]
},
{
  test: true,
  key: [{
    yes: true,
    no: null
  }]
},
{
  test: null,
  key: [{
    yes: null,
    no: null
  }]
}
];

我想返回一个数组,它只包含 test 为真(例如 1)的项。 test 中的 key 数组将只包含具有 key.yes 真值的对象。

所以预期的输出是:

[
   {
     test: 1,
     key: [{yes: true, no: null},{yes: true, no: null}]
   },
   {
     test: true,
     key: [{yes: true, no: null}]
   }
];

我试图通过使用像这样的简单过滤器来实现这一点:

const filtered = test.filter(obj => obj.test && obj.key.filter(item => item.yes).length > 0)

但这也会返回 key 数组的值,这些值是 false

有什么想法吗?

最佳答案

你需要得到一个新的外部数组和新的内部数组,因为外部过滤不会改变内部数组。如果改变内部数组并过滤外部数组,则会改变给定的数据。

要获得独立的结果,您可以检查 test 和 if truthy 过滤器 key 并为结果集获取一个新对象。

var test = [{ test: 1, key: [{ yes: true, no: null }, { yes: true, no: null }, { yes: false, no: null }] }, { test: true, key: [{ yes: true, no: null }] }, { test: null, key: [{ yes: null, no: null }] }],
    result = test.reduce((r, { test, key }) => {
        if (test) {
            r.push({ test, key: key.filter(({ yes }) => yes) });
        }
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 过滤特定值的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53083804/

相关文章:

javascript - 主干中的触发器和事件有什么区别?

javascript - 将 $.ajax 分配给变量

javascript - d3 如何每行渲染 15 个圆圈

javascript - 我的加载更多功能适用于单击按钮,但不适用于滚动

javascript - 如何更改谷歌甘特图字体?

Java分隔符读取文本文件

JavaScript如何获取变量(对象类型)属性名称?

圆形数组实现

php - array_unique 和 preg_split PREG_SPLIT_NO_EMPTY 的等效项

java - 异构数组的意义何在?