【问题标题】:How to find if a specific key is true in Array of objects如何在对象数组中查找特定键是否为真
【发布时间】:2020-05-19 15:24:49
【问题描述】:

我有这个数组,如果有一个等于 9 的“三”,我想得到一个布尔值(真)

myArr = [ { 苹果:6个, 篮子: [ { 一:1, 二:2, 三:3 }, { 一:4, 二:5, 三:6 } ] }, { 苹果:9, 篮子: [ { 一:1, 二:2, 三:3 }, { 一:4, 二:5, 三:9 } ] } ]

我尝试了什么:

enter code here

this.myArr.forEach( data => {
      if(data.basket.filter(cur => cur.one === 0 || cur.three === 9)) {
       console.log('true')
      }
    })

由于某种原因,我不知道为什么,这总是记录为真。

【问题讨论】:

    标签: javascript arrays typescript object ecmascript-6


    【解决方案1】:

    .filter 将始终返回一个 array 通过测试的元素,并且数组是真实的。即使没有元素通过测试,数组仍然是真的:

    const arr = [1, 2, 3].filter(() => false);
    if (arr) {
      console.log('truthy');
    }

    改用.some,看看是否至少有一个元素通过了测试:

    const myArr = [{
      apple: 6,
      basket: [{
        one: 1,
        two: 2,
        three: 3
      }, {
        one: 4,
        two: 5,
        three: 6
      }]
    }, {
      apple: 9,
      basket: [{
        one: 1,
        two: 2,
        three: 3
      }, {
        one: 4,
        two: 5,
        three: 9
      }]
    }]
    
    myArr.forEach(data => {
      if (data.basket.some(cur => cur.one === 0 || cur.three === 9)) {
        console.log('true');
      }
    });

    【讨论】:

    • 如果 some() 找到符合条件的值,它不会停止循环吗?非常感谢
    • 是的,但这就是你想要的,对吧?正如你所说:如果有一个等于 9 的“三”,我想得到一个布尔值(真)
    【解决方案2】:

    filter返回数组并使用find,它将返回匹配的项目或不匹配时返回null。

    在您的代码中,只需将 filter 更改为 find 即可。

    const myArr = [
      {
        apple: 6,
        basket: [
          { one: 1, two: 2, three: 3 },
          { one: 4, two: 5, three: 6 }
        ]
      },
      {
        apple: 9,
        basket: [
          { one: 1, two: 2, three: 3 },
          { one: 4, two: 5, three: 9 }
        ]
      }
    ];
    
    const items = myArr.map(data =>
      data.basket.find(cur => cur.one === 0 || cur.three === 9) ? "true" : "false"
    );
    
    console.log(items);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-05
      • 2019-03-31
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多