首页 > 解决方案 > How to verify a key exists in an array

问题描述

I have this variable:

var teams = [{manutd: true, barcelona: true, real: false}];

Given a string, I want to know if there is an entry in team's entries. So If I have:

var team = "real"

I want to query the "teams" and get true as "real" is one of the keys in the array. I have tried with includes but it fails. Maybe because the keys are not strings?

标签: javascript

解决方案


Using Object.keys, you can get the keys of the object item in an array.

var teams = [{manutd: true, barcelona: true, real: false}];
var team = 'real';

const isExisted = teams.some((item) => Object.keys(item).includes(team));
console.log(isExisted);


推荐阅读