繁体   English   中英

过滤嵌套数组以获取特定值

[英]Filter nested array for specific value

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

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真实值的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以及是否为真过滤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; } 

您还必须过滤每个单独的key数组。

// array where `test` is truthy
const filtered = test.filter(({ test }) => !!test);

// array where sub-arrays are filterd
const final = filtered.map(({ key }) => key.filter(({ yes }) => !!yes));

您应该首先过滤主数组,然后重新映射到新的过滤子数组,例如:

const filtered = test
   .filter(obj => obj.test && obj.key.some(item => item.yes))
   .map(d => {d.test, key: d.key.filter(item => item.yes));

或者可能是通过key.yes过滤数组。

const filtered = test
   .filter(obj => obj.test)
   .map(d => {d.test, key = d.key.filter(item => item.yes))
   .filter(s => s.key);

暂无
暂无

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

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