【问题标题】:How to check if key value pair in a array of objects in empty using react or javascript?如何使用反应或javascript检查对象数组中的键值对是否为空?
【发布时间】:2019-05-03 14:01:28
【问题描述】:

您好,我有如下数据,

data = [
  { 
    attributes: [{key: '', value: ''}, {key: 'name1', value: ''}],
    info: '',
    meshes: [],
  }
  {
   attributes: [{key: '', value: ''}, {key: '', value: ''}],
   info: '',
   meshes: [],
  }
   .....so on.... 
  ]

所以从上面的数据我想检查每个属性的键和值是否为空或未定义。我该如何检查。有人可以帮我解决这个问题。谢谢。

【问题讨论】:

  • 你尝试了什么?你期待什么结果?是否要过滤data?如果数组中的任何对象不符合您的条件,您是否需要布尔结果?
  • 遍历data并检查对象属性attributes
  • 空字符串和undefined都是假的
  • data.every(x => x.every(a => a.key === '' && a.value === ''))
  • 这似乎是正确的,谢谢。

标签: javascript reactjs


【解决方案1】:

这里有类似的SO post

试试下面的代码:

function isEmptyObject(o) {
    return Object.keys(o).every(function(x) {
        return o[x]===''||o[x]===null;  // or just "return o[x];" for falsy values
    });
}

const isEmpty = Object.values(object).every(x => (x === null || x === ''));

【讨论】:

    【解决方案2】:

    Firstly, iterate over data,然后,check length of attribute array

    data.forEach(attr => {
      if(attr.length > 0){
        // attr contains key and value
      }
    })
    

    【讨论】:

      【解决方案3】:
      for (let x in data) {
        for (let y in data[x].attributes) {
          if ((key === '') || (value === '')) {
            return ('data:' + x + 'attribute:' + y + 'missing key or value');
          }
        }
      }
      

      未经测试。 循环遍历所有数据和属性以测试空键/值。你可以添加一个额外的 else if 来分别检查 value 和 key。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-07
        • 2018-09-29
        • 2021-05-12
        • 2021-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多