【问题标题】:How to check particular key value length in array of javascript [closed]如何检查javascript数组中的特定键值长度[关闭]
【发布时间】:2019-08-22 17:11:44
【问题描述】:

我收到如下回复。

[
  {
    id: '508',
    class: 'class1',
    value: '0',
    profit: '2,
    color: 'black'
  },
  {
    id: '509',
    class: 'class2',
    value: '0',
    profit: '0',
    color: 'black'
  },
  {
    id: '510',
    class: 'class3',
    value: '0',
    profit: '0',
    color: 'black'
  },
  {
    id: '511',
    class: 'class',
    value: '0',
    profit: '2.40',
    color: 'black'
  }
]

我必须检查 profit 密钥长度是否超过 2 个索引某些条件或者其他条件。 注意:如果利润的值为0,那么它只会被认为是空的。

为此,我做了如下操作。

const profitArrayLength = sortedProfitData.keys('profit').length;
console.log('profitArrayLength is', profitArrayLength);

但是,它在控制台中显示为未定义。

【问题讨论】:

  • “密钥长度”是什么意思?
  • 长度是什么意思?字符串长度?检查后应该怎么做?你试过什么?请突出显示“我必须检查利润键长度是否超过2个索引其他条件。”
  • 你的意思是检查profit是否为两位数(profit >= 10)?
  • 我只想检查利润键是否具有除 0 以外的真实值。并且该键值的长度是否大于 1。就是这样。
  • @NinaScholz 我试过 const profitArrayLength = sortedProfitData.keys('profit').length;显示未定义

标签: javascript arrays sorting react-native


【解决方案1】:

您可以使用Array#filter 方法,在过滤器回调中定义检查属性和检查值。

let data = [
  {
    id: '508',
    class: 'class1',
    value: '0',
    profit: '2',
    color: 'black'
  },
  {
    id: '509',
    class: 'class2',
    value: '0',
    profit: '0',
    color: 'black'
  },
  {
    id: '510',
    class: 'class3',
    value: '0',
    profit: '0',
    color: 'black'
  },
  {
    id: '511',
    class: 'class',
    value: '0',
    profit: '2.40',
    color: 'black'
  }
];

let key  = 'profit';

let len = data.filter(o=> key in o && o[key] != 0 ).length

console.log(len);

console.log('Length is greater than 1   : ',  len > 1);

【讨论】:

    【解决方案2】:

    我不完全确定您在问什么,但听起来好像您想查看具有正利润的对象的数量。为此,您需要使用过滤器操作。 Filter 对数组进行操作,根据条件检查每个元素,然后从满足该条件的元素中返回一个新数组。之后,您可以检查该数组的长度以查看有多少元素满足该条件。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

    这是一个示例用法,您应该尝试理解它以应用于您检查有多少项目具有正利润的情况。在这种情况下,我们有值 a、b 和 c 的对象。在我的假例子中,我将过滤掉所有具有负“b”值的项目,看看我们有多少。然后,如果我们有超过 2 个,我们输入一个代码块。

    let arrayToFilter = [{
        a: 0,
        b: 0,
        c: '',
    }, {
        a: 0,
        b: -1,
        c: '',
    }, {
        a: 0,
        b: -7,
        c: '',
    }, {
        a: 0,
        b: 0,
        c: '',
    }];
    
    let filteredArray = arrayToFilter.filter(function(arrayItem){
        return arrayItem.b < 0;
    });
    
    if(filteredArray.length >=2){
        // do something
    }
    

    希望对你理解这个数组操作有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      相关资源
      最近更新 更多