Search code examples
javascriptobjecthasownproperty

How to differentiate between property and value passed in a function together


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.


Solution

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

    console.log(Object.getOwnPropertyNames(source));
    // ['last']