javascript - 过滤对象数组中的 bool 值

标签 javascript arrays filter

我有一个这样的数组:

 const appoint =[
  { a: "asas",
    b:{au: false, h:false,l:true}
  },
  { a: "avd",
    b:{au: true, h:false,l:true}
  },
  { a: "as", b:{au: true, h:false,l:false}
  }];

当我访问 b 时,我想过滤虚假值,到目前为止,我没有像这样使用一系列 map() 成功地做到这一点:

const result = appoint.map(elem => elem.b.)
const finalresult = result.map(
         item =>item.filter(
              (item, value)=> item[value] === false )
          )

最佳答案

您可以先使用 map 获取一个仅包含 b 的新数组,然后使用 reduce 并在 reduce 回调中使用 for..in 迭代对象并获取为真的键

const appoint = [{
    a: "asas",
    b: {
      au: false,
      h: false,
      l: true
    }
  },
  {
    a: "avd",
    b: {
      au: true,
      h: false,
      l: true
    }
  },
  {
    a: "as",
    b: {
      au: true,
      h: false,
      l: false
    }
  }
];


let filtered = appoint.map(function(item) {
  return item.b;
}).reduce(function(acc, curr) {
  for (let keys in curr) {
    if (curr[keys]) {
      acc.push(keys)
    }
  }

  return acc;
}, []);
console.log(filtered)

关于javascript - 过滤对象数组中的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56807607/

相关文章:

javascript - polymer :无法从纸张输入元件获取输入

javascript - Passport deserializeUser() 永远不会通过 Axios http 请求调用

javascript - jQuery .one() 方法的问题

arrays - react : Update element of array without rerendering other array elements

pandas - 在多个条件下过滤数据框索引

javascript - jQuery 在值更改之前触发更改

javascript - 关闭模式并滚动到 div

arrays - 从每个数组中删除是否安全?

@ManyToOne 上的 Hibernate @Filter

javascript - (使用 JS 过滤)为什么 "#"不起作用,而字母表中的其他所有内容都起作用