oderfla
oderfla

Reputation: 1797

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?

Upvotes: 1

Views: 156

Answers (3)

Scriptkiddy1337
Scriptkiddy1337

Reputation: 791

var teams = [{manutd: true, barcelona: true, real: false}];
console.log(teams.find(v => v.hasOwnProperty('real')));

Upvotes: 5

Lyes
Lyes

Reputation: 477

Use Object.keys to get the keys and check using includes

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

    var exist  = Object.keys(teams[0]).includes('real')
 
    console.log(exist)   

Upvotes: 1

Derek Wang
Derek Wang

Reputation: 10204

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);

Upvotes: 7

Related Questions