Abhi
Abhi

Reputation: 13

How can I check whether a JavaScript object contains a value in it or not?

0:{date: "2021-1-9", views: 32109, clicks: 279, likes: 4391}
1: {date: "2021-1-10", views: 127568, clicks: 691, likes: 8471}
2: {date: "2021-1-11", views: 17304, clicks: 94, likes: 764}
3: {date: "2021-1-12", views: 11008, clicks: 49, likes: 421}

0: {date: "2021-1-9", views: 32109, clicks: 279}
1: {date: "2021-1-10", views: 127568, clicks: 69}
2: {date: "2021-1-11", views: 17304, clicks: 94}
3: {date: "2021-1-12", views: 11008, clicks: 49}

0: {date: "2021-1-9", views: 32109, likes: 4391}
1: {date: "2021-1-10", views: 127568,likes: 8471}
2: {date: "2021-1-11", views: 17304, likes: 764}
3: {date: "2021-1-12", views: 11008, likes: 421}

I have the above data, as you can see some don't have likes, some don't have clicks element, so I want to check whether they exist in the arrays or not and print as false for the particular element which does not exist in the array.

Upvotes: 1

Views: 82

Answers (1)

Aalexander
Aalexander

Reputation: 5004

Object.prototype.hasOwnProperty()

You can check with the method hasOwnProperty() if the object has the key or not.

const obj = [{
    date: "2021-1-9",
    views: 32109,
    clicks: 279,
    likes: 4391
  },
  {
    date: "2021-1-10",
    views: 127568,
    clicks: 691,
    likes: 8471
  },
  {
    date: "2021-1-11",
    views: 17304,
    clicks: 94,
    likes: 764
  },
  {
    date: "2021-1-12",
    views: 11008,
    clicks: 49,
    likes: 421
  },

  {
    date: "2021-1-9",
    views: 32109,
    clicks: 279
  },
  {
    date: "2021-1-10",
    views: 127568,
    clicks: 69
  },
  {
    date: "2021-1-11",
    views: 17304,
    clicks: 94
  },
  {
    date: "2021-1-12",
    views: 11008,
    clicks: 49
  },

  {
    date: "2021-1-9",
    views: 32109,
    likes: 4391
  },
  {
    date: "2021-1-10",
    views: 127568,
    likes: 8471
  },
  {
    date: "2021-1-11",
    views: 17304,
    likes: 764
  },
  {
    date: "2021-1-12",
    views: 11008,
    likes: 421
  }
]

let propToLookFor = "likes";

obj.forEach((x) => {
      if (x.hasOwnProperty(propToLookFor)) {
          console.log("True");
        }else{
        console.log("False");
        }
      })

Upvotes: 1

Related Questions