0

So I have this function that I wish to spit out some object information if there is something in it. But I am stuck. Anyone know what the problem is?

function ifExist(property) {
    if ( randomObj.property === "" ) {
        message += "";
    } else {
        message += "<span class='propString'>" + randomObj.property + "</p>";
    }
    return message;
}

ifExist(citation);
ifExist(year);

Thanks in forehand!

3 Answers3

2

Use bracket notation for referencing changing keys: randomObj[property] That should allow you to use dynamic property name to pull values from keys on your object.

Using randomObj.property (dot notation) will literally find the key named property on your randomObject.

In addition, make sure to pass your keys in as strings:

ifExist("citation");
ifExist("year");

As mentioned by Ovér Flôwz, it's also a smart idea to make sure that key exists on your object before trying to process any data that you can't guarantee exists.

Alex Johnson
  • 1,504
  • 13
  • 20
  • Would me telling you that I am working with an array object make any difference..?? – S. Andersson Jun 07 '16 at 19:58
  • Can you give me an example of this array? If you're using arrays vs. key/value objects, you'll have to make some minor changes in how you look up the desired value. Related link: http://stackoverflow.com/questions/8067590/associative-array-versus-object-in-javascript – Alex Johnson Jun 07 '16 at 20:02
  • var people = [ { name: "John", lastname: "Hancock" }, { name: "Peter", lastname: "Parker" } ]; – S. Andersson Jun 08 '16 at 05:25
1

try:

function ifExists(obj, property) {
    return obj.hasOwnProperty(property);
}

var obj = { myprop: 'I got this.' };
console.log(ifExists(obj, 'myprop')); // also notice quotes.
Nika
  • 1,864
  • 3
  • 23
  • 44
0

First you need to determine what are you checking: whether the property does not exist at all on certain object or it equals null or empty ("") or undefined or false or 0 depending on its type.

In first case use object.hasOwnProperty(property). For all other cases (when you know the property exists):

if (!object[property]){
    //...
}

Better not to use single quotes inside tag attributes. The right way is:

var message += '<span class="propString">';

or you can escape it:

var message += "<span class=\"propString\">";
Oleg Mikhailov
  • 5,751
  • 4
  • 46
  • 54