微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 JS 对象数组中查找没有特定键属性的元素

如何解决在 JS 对象数组中查找没有特定键属性的元素

我有一个数组:

const Compress = require('compress.js');
    const compress = new Compress();
    const inputFile = document.querySelector('#upload')

    let dataList = new DataTransfer()
    console.log('datalist avant event');
    console.log(dataList);
    inputFile.addEventListener('change',(evt) => {
      const files = [...evt.target.files]

      compress.compress(files,{
        size: 3,// the max size in MB,defaults to 2MB
        quality: 0.75,// the quality of the image,max is 1,maxWidth: 1920,// the max width of the output image,defaults to 1920px
        maxHeight: 1920,// the max height of the output image,defaults to 1920px
        resize: true // defaults to true,set false if you do not want to resize the image width and height
      }).then((files) => {

        for (const file of files) {
          const base64str = file.data
          const imgExt = file.ext
          const blobFile = Compress.convertBase64ToFile(base64str,imgExt)
          const fileCompressed = new File([blobFile],file.alt,{ type: 'image/jpeg' })

          const image = new Image();
          image.src = file.prefix + file.data

          var span = document.createElement('span');

          span.innerHTML = [
            '<div class="col-xs-4 margin-table fond"  onclick="deletePhoto(this);">','<div style="position: absolute; margin-left: 75%;"><img src="/public/views/img/imageInsert/trash.png" width="15px"></div>','<input type="hidden" name="name_files" value="',fileCompressed.name,'" />','<img src="',image.src,'" height="auto" width="55%">','</div>'
          ].join('');
          document.getElementById('list').insertBefore(span,null);
        }
      })
    },false)

我想在这个列表中找到没有属性“Name”的对象。

我尝试做 [ 0 { Id : 01 country : "Algery" name: "Amnesty" },1 { Id : 02 country : "USA" name: "Alarmy" },2 { Id : 03 country : "Alaska" } ]

但它不起作用..这里有人有想法吗?

解决方法

该代码仅适用于虚假 name。要检查属性是否存在,您可以使用 in operator

const
    array = [{ Id: 01,country: "Algery",name: "Amnesty" },{ Id: 02,country: "USA",name: "Alarmy" },{ Id: 03,country: "Alaska" }];

console.log(array.find(person => !('name' in person)));

这种方法只返回第一个找到的项目。要获取所有项目,您可以应用 Array#filter 获取数组。

,

你可以这样做:

const arr = [{ Id: 01,{ Id:02,country:"Alaska" }];

console.log(arr.find(obj => !('name' in obj)));

,

除了上面提到的方法,另一种方法是使用 hasOwnProperty 方法

供您参考:

for ( var key in jsonArray) {
  if (!jsonArray[key].hasOwnProperty("name")) {
      console.log(jsonArray[key]);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。