0

I need to check if objects in an array to see if they include a property, and if so, whether the properties' values match.

The property and value are given together in the function call:

whatIsInAName(
    [
        { first: "Romeo", last: "Montague" }, 
        { first: "Mercutio", last: null }, 
        { first: "Tybalt", last: "Capulet" }
    ], 
    { last: "Capulet" }); //Property: last, value: Capulet.

The function definition:

function whatIsInAName(collection, source) {

I couldn't find anyway to separate the property from the value (they are both inside of source) so that I can first check if the property exists with hasOwnProperty and if so, then compare the values.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
tamir
  • 45
  • 4
  • In your real code, the property name in `source` (`last`) is unknown to you? – Teemu Jan 13 '17 at 22:04
  • You can get all of the properties of any object using `Object.keys()`, as indicated by [this question](http://stackoverflow.com/q/4260308/215552)... – Heretic Monkey Jan 13 '17 at 22:11
  • Use a `for-in` loop. –  Jan 13 '17 at 22:11
  • @Teemu: Yes, it is unknown. That's the problem. I know how to check whether one of the array's object has a certain property name or no- But I don't know how to separate `last` from `Capulet` in `source` – tamir Jan 13 '17 at 22:16

1 Answers1

0

You can use Object.getOwnPropertyNames(). It returns an array of property names of the object.

console.log(Object.getOwnPropertyNames(source));
// ['last']
Santanu Biswas
  • 4,699
  • 2
  • 22
  • 21