【问题标题】:Check if any of the specific key has a value in JavaScript array of object检查任何特定键是否在对象的 JavaScript 数组中具有值
【发布时间】:2017-07-12 23:07:29
【问题描述】:

我想检查是否有任何特定键在 JavaScript 对象数组中具有值。

myArray = [ {file:null}, {file:hello.jpg}, {file:null}] ;

file 有值所以返回true 否则返回false。 如何以编程方式检查?

【问题讨论】:

  • obj.key === 'value'?另外 - for 循环。
  • 没有 for 循环。但可能正在使用过滤器。
  • 如果我理解正确,您可以使用Array#some() developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。问题还是有点模糊
  • "没有 for 循环" --- 为什么?在使用Array.prototype.some(或其他数组函数)之前,您应该学习如何使用循环。
  • 同意 zerkms ...首先学习如何使用循环来做这些事情,

标签: javascript ecmascript-6


【解决方案1】:

由于null 是一个虚假值,您可以使用双重否定来检查它是否包含一个值 或者它是否为空 (null)。

let myArray = [ {file:null}, {file:'hello.jpg'}, {file:null}];

const check = arr => arr.map(v => !!v.file);

console.log(check(myArray));

【讨论】:

  • 你能解释一下这行吗, const check = arr => arr.map(v => !!v.file);
  • @kaws 双重否定。所有值都更改为布尔值。如果它有值,则返回true。如果它有null、空字符串或undefined,它将返回false
  • 如果您在我的其他问题的答案中发表您的评论会很好。
  • @kaws greg 在他的回答中提到了我的评论,无论如何你接受了他的回答。下次我会做一个完整的答案:)
  • myArray.filter(x => !!x.file).length;无需地图即可工作
【解决方案2】:

试试这个:

var myArray = [ {file: null}, {file: 'hello.jpg'}, {file: null}];
for(var i = 0; i < myArray.length; i++) {
    if(myArray[i].file != null) {
        console.log(myArray[i]);
    }
}

【讨论】:

    【解决方案3】:

    使用Array.prototype.some() 测试数组的任何元素是否符合条件。

    myArray = [{
      file: null
    }, {
      file: "hello.jpg"
    }, {
      file: null
    }];
    var result = myArray.some(e => e.file);
    console.log(result);

    【讨论】:

      【解决方案4】:

      你想看看map/filter/reduce,网上有很多解释,比如https://code.tutsplus.com/tutorials/how-to-use-map-filter-reduce-in-javascript--cms-26209

      在你的情况下,你想映射:

      items = myArray.map(item => !!item.file);
      

      【讨论】:

        猜你喜欢
        • 2019-03-31
        • 1970-01-01
        • 2019-12-15
        • 1970-01-01
        • 1970-01-01
        • 2018-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多