【问题标题】:filter value of properties of an array when properties are not the same当属性不相同时过滤数组属性的值
【发布时间】:2018-03-28 07:39:28
【问题描述】:
const myArray = [ { status: null }, { rooms: 2 }, { bathrooms: 3 }, { vaccum: null } ]

这是数组,我想过滤 null 的值并从数组中排除对象,无论属性是什么。

由于属性不一样我不能去:

const filteredArray = myArray.filter(property => {
    property.status == null
})

【问题讨论】:

    标签: javascript arrays filter ecmascript-6


    【解决方案1】:

    您可以通过根据对象中的值进行过滤来做到这一点,无论它们中的任何一个是否为null

    const myArray = [{
      status: null
    }, {
      rooms: 2
    }, {
      bathrooms: 3
    }, {
      vaccum: null
    }];
    
    let result = myArray.filter( o => {
      return !Object.values(o).includes(null)
    });
    
    console.log(result)

    Object.values 并非在所有浏览器中都支持,但可以很容易地被旧浏览器的简单循环替换

    const myArray = [{
      status: null
    }, {
      rooms: 2
    }, {
      bathrooms: 3
    }, {
      vaccum: null
    }];
    
    var result = myArray.filter( o => {
      for (key in o) {
      	if ( o[key] === null ) return false;
      }
      return true
    });
    
    console.log(result)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-07
      • 2015-10-13
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2019-05-04
      • 2019-10-14
      • 1970-01-01
      相关资源
      最近更新 更多