peace_love
peace_love

Reputation: 6471

How can I check if object contains a certain key?

This is my object data:

[{id:1, name:"Cat", category:{id:2, name:"Animals"}}]

I want to check if it contains the key category.

This is my approach:

if (data.hasOwnProperty("category")) {
console.log("data contains category");
}else {
  console.log("data does not contain category");
}

The output is:

data does not contain category

Should be the opposite...

Upvotes: 0

Views: 98

Answers (4)

Code Maniac
Code Maniac

Reputation: 37755

You need to loop through array elements. and you can destructure assignment

let arr = [{id:1, name:"Cat", category:{id:2, name:"Animals"}}]

arr.forEach(({category})=>{
  if (category !== undefined) {
   console.log("data contains category");
  }else {
   console.log("data does not contain category");
  }
})

Upvotes: 1

Ele
Ele

Reputation: 33726

That's an array with only one index, so you can do this using the operator in:

"category" in data[0] // That checks if the property "category" exists.

If you have more than one index, you should loop that array.

The operator in also checks for inherited properties.

let data = [{id:1, name:"Cat", category:{id:2, name:"Animals"}}];
data.forEach((o, i) => console.log("Index:", i, " - Has category?:", "category" in o));

Upvotes: 0

slider
slider

Reputation: 12990

You can also use some to check if any object in your array matches a certain condition:

var data = [{
  id: 1,
  name: "Cat",
  category: {
    id: 2,
    name: "Animals"
  }
}];

var hasCategory = data.some(k => k.hasOwnProperty('category'));

if (hasCategory) {
  console.log("data contains category");
} else {
  console.log("data does not contain category");
}

Upvotes: 1

brk
brk

Reputation: 50291

You need to iterate your array. So you can put the code inside a forEach

let k = [{
  id: 1,
  name: "Cat",
  category: {
    id: 2,
    name: "Animals"
  }
}]

k.forEach(function(data) {
  if (data.hasOwnProperty("category")) {
    console.log("data contains category");
  } else {
    console.log("data does not contain category");
  }
})

If you dont prefer to iterate you need to pass the index , since data is an array of object.

let data = [{
  id: 1,
  name: "Cat",
  category: {
    id: 2,
    name: "Animals"
  }
}]


if (data[0].hasOwnProperty("category")) {
  console.log("data contains category");
} else {
  console.log("data does not contain category");
}

Upvotes: 2

Related Questions