Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

arrays - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...