首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何检查一个值是否存在于包含多个对象的数组中?

如何检查一个值是否存在于包含多个对象的数组中?
EN

Stack Overflow用户
提问于 2018-07-25 02:50:25
回答 4查看 1.6K关注 0票数 0

所以我的数组看起来像这样:

代码语言:javascript
复制
let array = [
    {"object1":1},
    {"object2":2},
    {"object3":3}
];

我想要做的是检查,例如,是否存在"object1“。我更喜欢的方式是纯Javascript。

我对大块数据执行此操作,因此我的代码需要如下所示:

代码语言:javascript
复制
if ("opensprint1" in array){
  console.log("yes, this is in the array");
} else {
  console.log("no, this is not in the array");
};

注意:我尝试过在JS和(hasOwnProperty)中使用( in )函数,但都没有成功。

有什么想法吗?

EN

回答 4

Stack Overflow用户

发布于 2018-07-25 03:15:57

代码语言:javascript
复制
if ("opensprint1" in array){

它检查数组键,因此它将与以下命令一起工作:

代码语言:javascript
复制
if ("0" in array){

但实际上,您需要检查一些数组元素是否获得了该键:

代码语言:javascript
复制
if(array.some( el => "opensprint1" in el))
票数 1
EN

Stack Overflow用户

发布于 2018-07-25 02:58:09

您正在尝试过滤对象数组。您可以将一个自定义函数传递给Array.prototype.filter,定义一个自定义搜索函数。看起来你想要根据关键字的存在进行搜索。如果返回任何内容,则该键存在于对象数组中。

代码语言:javascript
复制
let array = [{
    "object1": 1
  },
  {
    "object2": 2
  },
  {
    "object3": 3
  }
];

const filterByKey = (arr, keyName) =>
  array.filter(obj => Object.keys(obj).includes(keyName)).length > 0;

console.log(filterByKey(array, 'object1'));
console.log(filterByKey(array, 'object5'));

这大致相当于:

代码语言:javascript
复制
let array = [{
    "object1": 1
  },
  {
    "object2": 2
  },
  {
    "object3": 3
  }
];

const filterByKey = (arr, keyName) => {
  // iterate each item in the array
  for (let i = 0; i < arr.length; i++) {
    const objectKeys = Object.keys(arr[i]);
    // take the keys of the object
    for (let j = 0; j < objectKeys.length; j++) {
      // see if any key matches our expected
      if(objectKeys[i] === keyName)
        return true
    }
  }
  // none did
  return false;
}

console.log(filterByKey(array, 'object1'));
console.log(filterByKey(array, 'object5'));

票数 0
EN

Stack Overflow用户

发布于 2018-07-25 03:02:11

这可能会对你有帮助

代码语言:javascript
复制
let array = [
    {"object1":1},
    {"object2":2},
    {"object3":3}
];

let targetkey = "opensprint1";
let exists  = -1;
for(let i = 0; i < array.length; i++) {
    let objKeys = Object.keys(array[i]);
    exists = objKeys.indexOf(targetkey);
    if (exists >= 0) {
        break;
    }
}

if (exists >= 0) {
    console.log("yes, this is in the array");
} else {
   console.log("no, this is not in the array");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51505647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档